Spaces:
Sleeping
Sleeping
File size: 2,370 Bytes
60a68a6 398a38a 60a68a6 398a38a 0dbd16b 398a38a 60a68a6 398a38a 60a68a6 398a38a 60a68a6 |
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 |
from fastapi import FastAPI, Response, Request, Header, Form, UploadFile, Body, BackgroundTasks
from pydantic import BaseModel
from fastapi.responses import FileResponse
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import RedirectResponse
from cardtagger import cardtagger
import io
from PIL import Image
import os, time
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
)
# API_TOKEN = os.environ["API_TOKEN"]
API_TOKEN = '34dsadfF$$%#$TGREGEFGE%Q*)(*&%'
# ---------------------------------------------------------------------------
# - Token auth method -
# ---------------------------------------------------------------------------
def check_auth(authorization_header):
if authorization_header == API_TOKEN :
return True
else:
return False
# ---------------------------------------------------------------------------
# - Delete cache files after 30 days -
# ---------------------------------------------------------------------------
def delete_old_files():
path = "./tmp"
now = time.time()
for filename in os.listdir(path):
filestamp = os.stat(os.path.join(path, filename)).st_mtime
filecompare = now - 14 * 86400
if filestamp < filecompare:
print(filename)
os.remove(os.path.join(path, filename))
@app.on_event("startup")
def startup_event() :
'''
Create out dir
'''
if not os.path.exists("/tmp"):
os.makedirs("/tmp")
@app.get("/")
async def root():
response = RedirectResponse(url='/docs')
return response
@app.post("/cardtagger")
async def resolution(request : Request, background_tasks: BackgroundTasks, response: Response, data: UploadFile = Form(...)):
authorization_token = request.headers.get("Authorization", None)
# check_token = check_auth(authorization_token)
check_token = True
if check_token:
image = io.BytesIO(await data.read())
image.seek(0)
result = cardtagger(image.read())
background_tasks.add_task(delete_old_files)
return result
else :
response.status_code = 401
return response
#uvicorn server:app --host 0.0.0.0 --port 5050 --workers 4 |