89 lines
2.8 KiB
Python
89 lines
2.8 KiB
Python
import os
|
|
import uuid
|
|
from io import BytesIO
|
|
|
|
import numpy as np
|
|
from PIL import Image
|
|
from fastapi import FastAPI, UploadFile
|
|
from fastapi.staticfiles import StaticFiles
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
|
def find_average_hex_color(image: Image.Image):
|
|
np_image = np.array(image)
|
|
average_color = np.mean(np_image, axis=(0, 1))
|
|
average_color_hex = '#{:02x}{:02x}{:02x}'.format(int(average_color[0]), int(average_color[1]),
|
|
int(average_color[2]))
|
|
return average_color_hex
|
|
|
|
|
|
def generate_uuid_from_file(file_content):
|
|
namespace_oid = uuid.UUID('6ba7b812-9dad-11d1-80b4-00c04fd430c8')
|
|
return uuid.uuid5(namespace_oid, str(file_content))
|
|
|
|
|
|
app = FastAPI(
|
|
prefix="/api",
|
|
tags=["Сервак для загрузки"],
|
|
)
|
|
|
|
origins = []
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=origins,
|
|
allow_credentials=True,
|
|
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
|
|
allow_headers=[
|
|
"Content-Type",
|
|
"Set-Cookie",
|
|
"Access-Control-Allow-Headers",
|
|
"Authorization",
|
|
"Accept"
|
|
],
|
|
)
|
|
|
|
app.mount("/static", StaticFiles(directory="app/static"), name="static")
|
|
|
|
|
|
@app.post('/upload_avatar', response_model=dict[str, str])
|
|
async def upload_avatar(file: UploadFile):
|
|
content = await file.read()
|
|
name = generate_uuid_from_file(content)
|
|
image = Image.open(BytesIO(content))
|
|
|
|
new_size = (512, 512)
|
|
resized_image = image.resize(new_size)
|
|
|
|
average_color_hex = find_average_hex_color(resized_image)
|
|
|
|
image_url = f'static/images/avatars/{name}_avatar.{image.format.lower()}'
|
|
with open('app/' + image_url, 'wb+') as file_object:
|
|
resized_image.save(file_object, format=image.format.lower())
|
|
return {'image_url': image_url, 'hex_color': average_color_hex}
|
|
|
|
|
|
@app.post('/upload_image', response_model=dict[str, str])
|
|
async def upload_image(file: UploadFile):
|
|
content = await file.read()
|
|
name = generate_uuid_from_file(content)
|
|
image = Image.open(BytesIO(content))
|
|
|
|
image_url = f'static/images/images/{name}_image.{image.format.lower()}'
|
|
with open('app/' + image_url, 'wb+') as file_object:
|
|
image.save(file_object, format=image.format.lower())
|
|
return {'image_url': image_url}
|
|
|
|
|
|
@app.post('/upload_background', response_model=list[str])
|
|
async def upload_background(file: UploadFile):
|
|
content = await file.read()
|
|
name = generate_uuid_from_file(content)
|
|
image = Image.open(BytesIO(content))
|
|
|
|
image_url = f'static/images/backgrounds/{name}_background.{image.format.lower()}'
|
|
with open('app/' + image_url, 'wb+') as file_object:
|
|
image.save(file_object, format=image.format.lower())
|
|
backgrounds = ['static/images/backgrounds/' + background for background in
|
|
os.listdir('app/static/images/backgrounds')]
|
|
return backgrounds
|