Переработал логику сейва

This commit is contained in:
urec56 2024-06-09 18:59:21 +05:00
parent 2c6f6321c5
commit 6077241c76

View file

@ -9,14 +9,6 @@ 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))
@ -27,22 +19,6 @@ app = FastAPI(
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")
@ -52,41 +28,20 @@ async def upload_avatar(file: UploadFile):
name = generate_uuid_from_file(content)
image = Image.open(BytesIO(content))
if image.format == 'GIF':
raise HTTPException(status_code=422, detail="С гифками ты идёшь нахуй")
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}
image_url = f"static/images/avatars/{name}_avatar.{image.format.lower()}"
resized_image.save(image_url)
return {"image_url": image_url}
@app.post('/upload_image', response_model=dict[str, str])
@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
image_url = f"static/images/images/{name}_image.{image.format.lower()}"
image.save(image_url)
return {"image_url": image_url}