-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
78 lines (51 loc) · 1.8 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
from fastapi import FastAPI, File, UploadFile, HTTPException, status
from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
from PIL import Image
from dotenv import load_dotenv
from deta import Deta
from io import BytesIO
import os
import logging
app = FastAPI()
load_dotenv()
PROJECT_KEY = os.environ.get('PROJECT_KEY')
deta = Deta(PROJECT_KEY)
drive = deta.Drive("webp_images")
@app.get("/", response_class=HTMLResponse)
def render():
return """
<form action="/upload" enctype="multipart/form-data" method="post">
<input name="file" type="file">
<input type="submit">
</form>
"""
@app.post("/upload")
def upload_image(file: UploadFile = File(...)):
if not file.filename.endswith(".webp") or not file:
raise HTTPException(status_code=400 , detail = "Select a '.webp' file")
webp_name = file.filename
image = file.file
try:
img = webp_to_png(image)
png_name = webp_name.replace(".webp", ".png")
res = drive.put(png_name, img)
return JSONResponse(status_code =status.HTTP_201_CREATED, content={"message": f"Image: '{res}' successfully uploaded."})
except:
return JSONResponse(status_code=500, content="There was an error converting or uploading the file")
@app.get("/convert/{name}")
def converter(name: str):
res = drive.get(name)
if res is None:
raise HTTPException(status_code=404, detail="Image not found")
return StreamingResponse(res.iter_chunks(1024), media_type="image/png")
def webp_to_png(image):
try:
img = Image.open(image)
img_io = BytesIO()
img.save(img_io , 'PNG')
img_io.seek(0)
except OSError:
print("Cannot convert")
finally:
img.close()
return img_io