from fastapi import FastAPI,UploadFile,File,status,HTTPException from fastapi.middleware.cors import CORSMiddleware import aiofiles import os import cv2 from extractpuzzle import extract_grid,get_text app = FastAPI() # for reading images in chunk CHUNK_SIZE = 1024 * 1024 * 2 app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], allow_credentials=True, ) # format the clue to match the JSON format def changeClueFormat(data): returnArr = [] for key,value in data.items(): returnArr.append(str(key)[:-1]+" "+value[1]) return returnArr @app.get("/") async def index(): return {"message": "Hello World"} @app.post("/parseImage/") async def upload(file: UploadFile = File(...)): try: filepath = os.path.join('./', os.path.basename(file.filename)) async with aiofiles.open(filepath, 'wb') as f: while chunk := await file.read(CHUNK_SIZE): await f.write(chunk) except Exception: raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail='There was an error uploading the file') finally: await file.close() img_array = cv2.imread(filepath,0) grid_data = {} clue_data = { 'clues':{ 'across':[], 'down':[] } } # try extracting the grid from the image try: # dict = { 'size' : size, 'grid' : grid, 'gridnums': grid_nums, 'across_nums': down_clue_num,'down_nums' : across_clue_num } grid_data = extract_grid(img_array) grid_data['gridExtractionStatus'] = "Passed" except Exception as e: grid_data['gridExtractionStatus'] = "Failed" # try extracting clues try: acrossClues, downClues = get_text(img_array) # { number : [column_of_projection_profile,extracted_text]} clue_data['clues']['across'] = changeClueFormat(acrossClues) clue_data['clues']['down'] = changeClueFormat(downClues) grid_data['clueExtractionStatus'] = "Passed" except Exception as e: grid_data['clueExtractionStatus'] = "Failed" grid_data['parsedFromImage'] = "True" grid_data.update(clue_data) print(grid_data) return grid_data