import os
from fastapi import FastAPI
from fastapi import File
import cv2
import numpy as np
import io
import uvicorn
from datetime import datetime

ROOT_DIR = os.path.abspath(os.curdir)



os.environ["config"]="{\"TZ\": \"Asia/Kolkata\", \"MONGO_URI\": \"mongodb://192.168.0.220:2717/admin\", \"MONGO_DATABASE\": \"ilens_ai\", \"MONGO_COLLECTION\": \"janusDeployment\", \"MONGO_KEY\": \"deploymentId\", \"MONGO_VALUE\": \"ACCCementCamera20_61275102\", \"MONGO_COLL\": \"serviceConfiguration\", \"MONGO_DB\": \"ilens_ai\"}"
from edge_engine.edge_processor import ExecutePipeline
from edge_engine.edge_processor import Pubs
from scripts import CementBagCounter
from edge_engine.common.config import EDGE_CONFIG
pubs = Pubs()
mod = CementBagCounter(config=EDGE_CONFIG,
                       model_config=EDGE_CONFIG["modelConfig"],
                       pubs=pubs,
                       device_id=EDGE_CONFIG['deviceId'])

app = FastAPI()



@app.post("/Text_recognition")
def extract_text_diectly(file: bytes = File(...)):

    try:
        stream = io.BytesIO(file)
        image = np.asarray(bytearray(stream.read()), dtype="uint8")
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)


        file="archive/sample_"+str(datetime.now())+".jpg"
        file=file.replace(" ","_")
        file=file.replace("-","_")
        file = file.replace(":", "_")
        cv2.imwrite(file, image)
        ex = ExecutePipeline(mod,image)
        ex.run_model()


        return mod.text_json
    except Exception as e:
        print(e)

if __name__ == '__main__':
    uvicorn.run("app:app", host="0.0.0.0", port=8290)

