Commit a6872d56 authored by shikhin-1998's avatar shikhin-1998

initial commit

parent 3c95fe7d
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
\ No newline at end of file
This diff is collapsed.
import uvicorn
from fastapi import FastAPI
from scripts.core.services.Text_Extraction_Service import router
from scripts.config.app_configurations import *
app = FastAPI()
app.include_router(router)
if __name__ == "__main__":
uvicorn.run("app:app", host=HOST, port=PORT)
[LOG]
log_level=INFO
base_path=logs/
file_name=structure
handlers=console,file
logger_name=structure
[SERVICE]
host=localhost
port=8200
[PATH]
model_path = scripts/utility/model/yolov8l_r1_r2_lp_best.pt
# YOLOv5 requirements
# Usage: pip install -r requirements.txt
# Base ----------------------------------------
matplotlib>=3.2.2
numpy>=1.18.5
opencv-python>=4.1.1
Pillow>=7.1.2
PyYAML>=5.3.1
requests>=2.23.0
scipy>=1.4.1
#torch>=1.7.0 # see https://pytorch.org/get-started/locally/ (recommended)
#torchvision>=0.8.1
tqdm>=4.64.0
# protobuf<=3.20.1 # https://github.com/ultralytics/yolov5/issues/8012
# Logging -------------------------------------
tensorboard>=2.4.1
# clearml>=1.2.0
# comet
# Plotting ------------------------------------
pandas>=1.1.4
seaborn>=0.11.0
# Export --------------------------------------
# coremltools>=6.0 # CoreML export
# onnx>=1.9.0 # ONNX export
# onnx-simplifier>=0.4.1 # ONNX simplifier
# nvidia-pyindex # TensorRT export
# nvidia-tensorrt # TensorRT export
# scikit-learn<=1.1.2 # CoreML quantization
# tensorflow>=2.4.1 # TF exports (-cpu, -aarch64, -macos)
# tensorflowjs>=3.9.0 # TF.js export
# openvino-dev # OpenVINO export
# Deploy --------------------------------------
# tritonclient[all]~=2.24.0
# Extras --------------------------------------
ipython # interactive notebook
psutil # system utilization
thop>=0.1.1 # FLOPs computation
# mss # screenshots
# albumentations>=1.0.3
# pycocotools>=2.0 # COCO mAP
# roboflow
python-dotenv==0.21.0
fastapi==0.86.0
python-multipart==0.0.5
click==8.1.3
h11==0.14.0
uvicorn==0.19.0
ultralytics
paddleocr==2.7.0.3
paddlepaddle==2.5.2
import configparser
config = configparser.ConfigParser()
config.read('conf/application.conf')
LOG_LEVEL = config.get('LOG', 'log_level')
LOG_BASEPATH = config.get('LOG', 'base_path')
LOG_FILE_NAME = LOG_BASEPATH + config.get('LOG', 'file_name')
LOG_HANDLERS = config.get('LOG', 'handlers')
LOGGER_NAME = config.get('LOG', 'logger_name')
HOST = config.get('SERVICE', 'host')
PORT = config.getint('SERVICE', 'port')
MODEL_PATH = config.get('PATH', 'model_path')
\ No newline at end of file
class BaseName:
baseurl = "/Text_Extraction"
class TEXT_EXTRACT:
text = BaseName.baseurl + "/value"
class Image:
upload="/upload_image"
from paddleocr import PaddleOCR
from ultralytics import YOLO
import torch
import cv2
from scripts.config.app_configurations import *
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# print(f'Using device: {device}')
def load_ocr_model():
ocr = PaddleOCR(use_angle_cls=True, lang='en')
return ocr
def load_yolo_model():
model = YOLO(MODEL_PATH).to(device)
return model
def predict(img_path, ocr, yolo_model):
img = cv2.imread(img_path)
results = yolo_model.predict(img, iou=0.7)
if results:
r1_txt = None
r2_txt = None
for r in results:
# annotator = Annotator(img)
boxes = r.boxes
for box in boxes:
b = box.xyxy[0] # get box coordinates in (top, left, bottom, right) format
# print("bb: ",b.tolist())
x1 = int(b[0])
y1 = int(b[1])
x2 = int(b[2])
y2 = int(b[3])
w = abs(x2 - x1)
h = abs(y2 - y1)
cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 0), 1)
# lp = img[max(y1 - 30, 0):min(y1+h + 30, img.shape[0]), max(x1 - 30, 0):min(x1+w + 30, img.shape[1])]
lp = img[y1:y1 + h, x1:x1 + w]
c = box.cls
# print("class: ", c)
# annotator.box_label(b, model.names[int(c)])
# img = annotator.result()
# cv2.imshow('YOLO V8 Detection', cv2.resize(img, (900, 600)))
if int(c) == 0:
result = ocr.ocr(lp, cls=True)
for idx in range(len(result)):
res = result[idx]
text_x = 10
text_y = 30
if res:
for ind, line in enumerate(res):
# print("line")
# print(line)
text_tuple = line[1]
if r1_txt is None:
r1_txt = text_tuple[0]
print("R1 TEXT: ", r1_txt)
text_conf = text_tuple[1]
elif int(c) == 1:
result = ocr.ocr(lp, cls=True)
for idx in range(len(result)):
res = result[idx]
text_x = 10
text_y = 30
if res:
for ind, line in enumerate(res):
# print("line")
# print(line)
text_tuple = line[1]
if r2_txt is None:
r2_txt = text_tuple[0]
print("R2 TEXT: ", r2_txt)
text_conf = text_tuple[1]
# cv2.putText(lp, txt, (text_x , text_y + ind*50), cv2.FONT_HERSHEY_SIMPLEX , 1, (255, 0, 0), 2, cv2.LINE_AA)
# cv2.imshow('detected LPR', lp)
# cv2.waitKey(0)
#
if r1_txt is not None and r2_txt is not None:
LP = f"{r1_txt} {r2_txt}"
# print("LP: ", LP)
return LP
return "Image Not Clear"
# result = ocr.ocr(img_path, cls=False,det=True,rec=True)[0]
# txts = [line[1][0] for line in result]
from fastapi import APIRouter
from fastapi import File
import cv2
import numpy as np
import io
from scripts.core.handler.Text_Extraction_Handler import load_ocr_model,load_yolo_model, predict
from scripts.logging.application_logging import logger
from scripts.config.app_constants import TEXT_EXTRACT
ocr = load_ocr_model()
yolo_model = load_yolo_model()
router = APIRouter()
@router.post(TEXT_EXTRACT.text)
def extract_license_number(file: bytes = File(...)):
try:
stream = io.BytesIO(file)
image = np.asarray(bytearray(stream.read()), dtype="uint8")
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imwrite("test.jpg", image)
image_path = "test.jpg"
text = predict(image_path, ocr, yolo_model)
logger.info("text detected")
return text
except Exception as e:
logger.error("Error is :{}".format(e))
import logging.handlers
import os
import sys
import time
from logging import StreamHandler
from scripts.config import app_configurations
LOG_HANDLERS = app_configurations.LOG_HANDLERS
log_level = app_configurations.LOG_LEVEL
log_file = os.path.join(app_configurations.LOG_FILE_NAME + "_" + time.strftime("%Y%m%d") + '.log')
logger = logging.getLogger(app_configurations.LOGGER_NAME)
logger.setLevel(log_level)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(module)s: %(funcName)s: '
'%(lineno)d - %(message)s')
if 'console' in LOG_HANDLERS:
# Adding the log Console handler to the logger
console_handler = StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# if 'file' in LOG_HANDLERS:
# # Adding the log file handler to the logger
# file_handler = logging.FileHandler(log_file)
# file_handler.setFormatter(formatter)
# logger.addHandler(file_handler)
\ No newline at end of file
test.jpg

550 KB

Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment