-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
147 lines (119 loc) · 4.97 KB
/
main.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import os
import io
import logging
from PIL import Image
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.exceptions import HTTPException
from fastapi.templating import Jinja2Templates
from starlette.responses import StreamingResponse
from application.inference import InferenceOnSingleImage
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
endpoint_prefix = os.environ.get("ENDPOINT_PREFIX", "/image-captioning")
app = FastAPI(docs_url=f"{endpoint_prefix}",
title="Image Captioning Application",
description="This is a simple FastAPI application for image captioning",
openapi_url=f"{endpoint_prefix}/openapi.json"
)
origins = [
"http://localhost:8081/image-captioning",
"http://0.0.0.0:8081/image-captioning"
"http://localhost:8081",
"http://0.0.0.0:8081"
"http://127.0.0.1:8081",
"http://127.0.0.1:8081/image-captioning",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["*"],
expose_headers=["Content-Disposition"],
max_age=3600,
)
templates = Jinja2Templates(directory="templates")
@app.post(f"{endpoint_prefix}/caption_image/", tags=["Image Captioning"]) # response_class=HTMLResponse)
async def image_file_text(image_file: UploadFile = File(...)):
logging.info(image_file.file)
try:
os.mkdir("./resources/image_file")
logging.info(os.getcwd())
except Exception as e:
logging.info(e)
file_path = os.path.join(os.getcwd(), "./resources/image_file", image_file.filename.replace(" ", "-"))
with open(file_path, 'wb+') as f:
f.write(image_file.file.read())
image = Image.open(os.path.join(file_path)).convert('RGB')
get_caption = InferenceOnSingleImage()
orig_image, sentence = get_caption.caption_sentence_from_upload(image)
output = {
"filename": image_file.filename,
"predicted_caption": sentence
}
logging.info(f"Prediction for {image_file} ...done!")
return output
# return templates.TemplateResponse("page.html", {"request": image_file.filename, "data": sentence})
@app.post(f"{endpoint_prefix}/upload_image/", tags=["Image Captioning"])
async def image_file_preview(image_file: UploadFile = File(...)):
logging.info(image_file.file)
try:
os.mkdir("./resources/image_file")
logging.info(os.getcwd())
except Exception as e:
logging.info(e)
file_path = os.path.join(os.getcwd(), "./resources/image_file", image_file.filename.replace(" ", "-"))
with open(file_path, 'wb+') as f:
f.write(image_file.file.read())
image = Image.open(os.path.join(file_path)).convert('RGB')
get_caption = InferenceOnSingleImage()
orig_image, sentence = get_caption.caption_sentence_from_upload(image)
output = {
"filename": image_file.filename,
"predicted_caption": sentence
}
image.thumbnail((200, 200))
buf = io.BytesIO()
image.save(buf, "JPEG")
buf.seek(0)
logging.info(f"Prediction for {image_file} ...done!")
return StreamingResponse(content=buf, media_type="image/jpeg", headers={"Content-Disposition": f"{output}"})
@app.post(f"{endpoint_prefix}/upload_image/metadata", tags=["Image Captioning"])
async def image_metadata(image_file: UploadFile = File(...)):
"""Endpoint to get image metadata and caption"""
try:
contents = await image_file.read()
image = Image.open(io.BytesIO(contents)).convert('RGB')
get_caption = InferenceOnSingleImage()
orig_image, sentence = get_caption.caption_sentence_from_upload(image)
return JSONResponse(content={
"filename": image_file.filename,
"predicted_caption": sentence
})
except Exception as e:
logging.error(f"Error processing image: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
@app.post(f"{endpoint_prefix}/upload_image/thumbnail", tags=["Image Captioning"])
async def image_thumbnail(image_file: UploadFile = File(...)):
"""Endpoint to get image thumbnail"""
try:
contents = await image_file.read()
image = Image.open(io.BytesIO(contents)).convert('RGB')
# Create thumbnail
image.thumbnail((200, 200))
buf = io.BytesIO()
image.save(buf, format="JPEG")
buf.seek(0)
return StreamingResponse(
content=buf,
media_type="image/jpeg",
headers={
"Content-Disposition": f'attachment; filename="thumbnail-{image_file.filename}"',
"Access-Control-Allow-Origin": "*",
"Access-Control-Expose-Headers": "Content-Disposition"
}
)
except Exception as e:
logging.error(f"Error processing image: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))