File size: 1,152 Bytes
571ee53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import io
import tempfile
from functools import lru_cache

import boto3
from config import Settings
from fastapi import FastAPI, UploadFile

from app import color


@lru_cache
def get_settings():
    return Settings()


settings = get_settings()

s3 = boto3.client(
    "s3",
    endpoint_url=settings.endpoint_url,
    aws_access_key_id=settings.aws_access_key_id,
    aws_secret_access_key=settings.aws_secret_access_key,
)


def old_photo_restoration(file):
    with tempfile.NamedTemporaryFile() as fp:
        fp.write(file.file.read())
        result = color(fp.name)

        if len(result) < 2:
            return None

        file_path = upload_to_s3(result[1])
        fp.close()
        return file_path


def upload_to_s3(file_path):
    with open(file_path, "rb") as file:
        file_content = file.read()

        s3.upload_fileobj(io.BytesIO(file_content), "old-photo-restoration", file.name)
        return f"{settings.cloud_flare_endpoint}/{file.name}"


app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.post("/upload")
def upload_image(file: UploadFile):
    return old_photo_restoration(file)