index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
28,619,743
|
QianrXU/Projects
|
refs/heads/master
|
/mysite/limin/apps.py
|
from django.apps import AppConfig
class LiminConfig(AppConfig):
name = 'limin'
|
{"/mysite/limin/views.py": ["/mysite/limin/models.py"]}
|
28,619,744
|
QianrXU/Projects
|
refs/heads/master
|
/mysite/limin/models.py
|
from django.db import models
# Create your models here.
class Topic(models.Model):
subject = models.CharField(max_length=255)
message = models.TextField(max_length=4000)
created_at = models.DateTimeField(auto_now_add=True)
|
{"/mysite/limin/views.py": ["/mysite/limin/models.py"]}
|
28,619,745
|
QianrXU/Projects
|
refs/heads/master
|
/mysite/limin/views.py
|
from django.shortcuts import render
from .models import Topic
def products(request):
return render(request, 'products.html')
def equipments(request):
return render(request, 'equipments.html')
def company(request):
topics = Topic.objects.all()
return render(request, 'company.html', {'topics': topics})
def purchase(request):
return render(request, 'purchase.html')
def contact(request):
return render(request, 'contact.html')
def product1(request):
return render(request, 'product1.html')
def product2(request):
return render(request, 'product2.html')
def product3(request):
return render(request, 'product3.html')
def product4(request):
return render(request, 'product4.html')
def product5(request):
return render(request, 'product5.html')
def product6(request):
return render(request, 'product6.html')
def product7(request):
return render(request, 'product7.html')
def product8(request):
return render(request, 'product8.html')
def product9(request):
return render(request, 'product9.html')
def topics(request, pk):
topic = Topic.objects.get(pk=pk)
return render(request, 'topics.html', {'topic': topic})
|
{"/mysite/limin/views.py": ["/mysite/limin/models.py"]}
|
28,619,746
|
QianrXU/Projects
|
refs/heads/master
|
/board/mysite/urls.py
|
from django.contrib import admin
from django.urls import path
from boards import views
from accounts import views as accounts_views
from django.contrib.auth import views as auth_views
from django.conf.urls import url
urlpatterns = [
path('', views.BoardListView.as_view(), name='home'),
path('test/', accounts_views.test, name="test"),
path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'),
path('signup/', accounts_views.signup, name='signup'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('boards/<int:pk>', views.TopicListView.as_view(), name='board_topics'),
path('boards/<int:pk>/new', views.new_topic, name='new_topic'),
path('admin/', admin.site.urls),
path('reset/',
auth_views.PasswordResetView.as_view(
template_name='password_reset.html',
email_template_name='password_reset_email.html',
subject_template_name='password_reset_subject.txt'
),
name='password_reset'),
path('reset/<uidb64>/<token>/',
auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html'),
name='password_reset_confirm'),
path('reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'),
name='password_reset_done'),
path('reset/complete/',
auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'),
name='password_reset_complete'),
path('board/<pk>/topics/<topic_pk>/posts/<post_pk>/edit/', views.PostUpdateView.as_view(), name='edit_post'),
path('settings/account/' , accounts_views.UserUpdateView.as_view(), name='my_account'),
url(r'^settings/password/$', auth_views.PasswordChangeView.as_view(template_name='password_change.html'),
name='password_change'),
url(r'^settings/password/done/$', auth_views.PasswordChangeDoneView.as_view(template_name='password_change_done.html'),
name='password_change_done'),
url(r'^boards/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/$', views.PostListView.as_view(), name='topic_posts'),
url(r'^boards/(?P<pk>\d+)/topics/(?P<topic_pk>\d+)/reply/$', views.reply_topic, name='reply_topic'),
]
|
{"/mysite/limin/views.py": ["/mysite/limin/models.py"]}
|
28,725,626
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/order_service/server.py
|
import logging
import grpc
import signal
import sys
import os
import argparse
import environ
import uuid
from concurrent import futures
from loguru import logger
BASE_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, BASE_DIR)
from order_service.proto import order_pb2_grpc
from order_service.handler.handler import OrderService, order_timeout
from order_service.settings import settings
from common.server import BaseServer
from common.grpc_health.v1 import health_pb2, health_pb2_grpc
from common.grpc_health.v1 import health
from rocketmq.client import PushConsumer
from grpc_opentracing import open_tracing_server_interceptor
from jaeger_client import Config
from grpc_opentracing.grpcext import intercept_server
class OrderServiceServer(BaseServer):
SERVICE_NAME = 'order-srv'
def __init__(self, host, port):
super(OrderServiceServer, self).__init__()
self.SERVICE_ID = self.SERVICE_NAME + "-" + f'{str(uuid.uuid4())}'
self.SERVICE_HOST = host
self.SERVICE_PORT = port
self.CONSUL_HOST = settings.data["consul"]["host"]
self.CONSUL_PORT = settings.data["consul"]["port"]
def onExit(self, signo, frame):
logger.info("Order Service terminate")
self.unregister()
sys.exit(0)
def serve(self):
config = Config(
config={ # usually read from some yaml config
'sampler': {
'type': 'const', # 全部
'param': 1, # 1 开启全部采样 0 表示关闭全部采样
},
'local_agent': {
'reporting_host': '192.168.0.14',
'reporting_port': '6831',
},
'logging': True,
},
service_name='order-srv',
validate=True,
)
tracer = config.initialize_tracer()
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=40))
tracing_interceptor = open_tracing_server_interceptor(tracer)
self.server = intercept_server(self.server, tracing_interceptor)
order_pb2_grpc.add_OrderServicer_to_server(OrderService(), self.server)
health_servicer = health.HealthServicer()
health_pb2_grpc.add_HealthServicer_to_server(health_servicer, self.server)
self.server.add_insecure_port(f'[::]:{self.SERVICE_PORT}')
signal.signal(signal.SIGINT, self.onExit)
signal.signal(signal.SIGTERM, self.onExit)
logger.info("Start Order Service at {}:{}".format(self.SERVICE_HOST, self.SERVICE_PORT))
self.server.start()
self.register()
#监听超时订单消息
consumer = PushConsumer("mxshop_order")
consumer.set_name_server_address(f"{settings.RocketMQ_HOST}:{settings.RocketMQ_PORT}")
consumer.subscribe("order_timeout", order_timeout)
consumer.start()
self.server.wait_for_termination()
consumer.shutdown()
if __name__ == "__main__":
logging.basicConfig()
parser = argparse.ArgumentParser()
parser.add_argument('--host', nargs="?",
type=str,
default=settings.HOST,
help="host")
parser.add_argument('--port',
nargs="?",
type=int,
default=50063,
help="port")
args = parser.parse_args()
server = OrderServiceServer(args.host, args.port)
server.serve()
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,627
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/userop_service/server.py
|
import consul
import grpc
import logging
import signal
import sys
import os
import argparse
import environ
import uuid
from concurrent import futures
import requests
from loguru import logger
BASE_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, BASE_DIR)
from userop_service.proto import address_pb2, message_pb2, userfav_pb2, address_pb2_grpc, userfav_pb2_grpc, \
message_pb2_grpc
from userop_service.handler.user_fav import UserFavServicer
from userop_service.handler.address import AddressServicer
from userop_service.handler.message import MessageServicer
from common.grpc_health.v1 import health_pb2, health_pb2_grpc
from common.grpc_health.v1 import health
from common.server import BaseServer
from userop_service.settings import settings
class UserOPServiceServer(BaseServer):
SERVICE_NAME = "userop-srv"
def __init__(self, host, port):
super(UserOPServiceServer, self).__init__()
self.SERVICE_ID = self.SERVICE_NAME + "-" + f'{str(uuid.uuid4())}'
self.SERVICE_HOST = host
self.SERVICE_PORT = port
self.CONSUL_HOST = settings.data["consul"]["host"]
self.CONSUL_PORT = settings.data["consul"]["port"]
logger.add("logs/userop_service_{time}.log")
def onExit(self, signo, frame):
logger.info("User service terminate")
self.unregister()
sys.exit(0)
def serve(self):
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=40))
address_pb2_grpc.add_AddressServicer_to_server(AddressServicer(), self.server)
userfav_pb2_grpc.add_UserFavServicer_to_server(UserFavServicer(), self.server)
message_pb2_grpc.add_MessageServicer_to_server(MessageServicer(), self.server)
health_servicer = health.HealthServicer()
health_pb2_grpc.add_HealthServicer_to_server(health_servicer, self.server)
self.server.add_insecure_port(f'[::]:{self.SERVICE_PORT}')
signal.signal(signal.SIGINT, self.onExit)
signal.signal(signal.SIGTERM, self.onExit)
logger.info("Start UserOP Srv Service at {}:{}".format(self.SERVICE_HOST, self.SERVICE_PORT))
self.server.start()
self.register()
self.server.wait_for_termination()
if __name__ == "__main__":
logging.basicConfig()
parser = argparse.ArgumentParser()
parser.add_argument('--host', nargs="?",
type=str,
default=settings.HOST,
help="host")
parser.add_argument('--port',
nargs="?",
type=int,
default=50066,
help="port")
args = parser.parse_args()
server = UserOPServiceServer(args.host, args.port)
server.serve()
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,628
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/goods_service/model/models.py
|
from peewee import *
from datetime import datetime
from goods_service.settings import settings
from playhouse.mysql_ext import JSONField
class BaseModel(Model):
add_time = DateTimeField(default=datetime.now())
is_deleted = BooleanField(default=False)
update_time = DateTimeField(default=datetime.now())
class Meta:
database = settings.DB
def save(self, *args, **kwargs):
if self._pk is not None:
self.update_time = datetime.now()
return super().save(*args, **kwargs)
@classmethod
def delete(cls, permanently=False):
if permanently:
return super().delete()
else:
return super().update(is_deleted=True)
def delete_instance(self, permanently=False, recursive=False, delete_nullable=False):
if permanently:
return self.delete(permanently).where(self._pk_expr()).execute()
else:
self.is_deleted = True
self.save()
@classmethod
def select(cls, *fields):
return super().select(*fields).where(cls.is_deleted==False)
class Category(BaseModel):
name = CharField(max_length=20, verbose_name="Name")
parent_category = ForeignKeyField("self", verbose_name="Parent category", null=True) #一级类别可以没有父类别
level = IntegerField(default=1, verbose_name="Category")
is_tab = BooleanField(default=False)
class Brands(BaseModel):
name = CharField(max_length=50, verbose_name="Name", index=True, unique=True)
logo = CharField(max_length=200, null=True, verbose_name="Logo", default="")
class Goods(BaseModel):
category = ForeignKeyField(Category, on_delete='CASCADE')
brand = ForeignKeyField(Brands, on_delete='CASCADE')
on_sale = BooleanField(default=True)
goods_sn = CharField(max_length=50, default="", verbose_name="Goods Number")
name = CharField(max_length=100)
click_num = IntegerField(default=0)
sold_num = IntegerField(default=0)
fav_num = IntegerField(default=0)
market_price = FloatField(default=0)
shop_price = FloatField(default=0)
goods_brief = CharField(max_length=200)
ship_free = BooleanField(default=True)
images = JSONField()
desc_images = JSONField()
goods_front_image = CharField(max_length=200)
is_new = BooleanField(default=False)
is_hot = BooleanField(default=False)
class GoodsCategoryBrand(BaseModel):
#品牌分类
id = AutoField(primary_key=True, verbose_name="id")
category = ForeignKeyField(Category, verbose_name="")
brand = ForeignKeyField(Brands, verbose_name="")
class Meta:
indexes = (
(("category", "brand"), True),
)
class Banner(BaseModel):
"""
轮播的商品
"""
image = CharField(max_length=200, default="", verbose_name="图片url")
url = CharField(max_length=200, default="", verbose_name="访问url")
index = IntegerField(default=0, verbose_name="Order")
if __name__ == "__main__":
# settings.DB.create_tables([Category,Goods, Brands, GoodsCategoryBrand, Banner])
pass
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,629
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/common/config/config_center.py
|
class ConfigCenter:
def __init__(self, *args, **kwargs):
pass
def __pull(self, id):
raise NotImplementedError
def __push(self, id):
raise NotImplementedError
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,630
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/user_service/handler/user.py
|
import grpc
import time
from datetime import date
from loguru import logger
from user_service.proto import user_pb2, user_pb2_grpc
from user_service.model.models import User
from peewee import DoesNotExist
from passlib.hash import pbkdf2_sha256
from google.protobuf import empty_pb2
from loguru import logger
class UserServicer(user_pb2_grpc.UserServicer):
def convert_user_to_rsp(self, user: User) -> user_pb2.UserInfoResponse:
user_info_rsp = user_pb2.UserInfoResponse()
user_info_rsp.id = user.id
user_info_rsp.password = user.password
user_info_rsp.mobile = user.mobile
user_info_rsp.role = user.role
if user.nick_name:
user_info_rsp.nickName = user.nick_name
if user.gender:
user_info_rsp.gender = user.gender
if user.birthday:
user_info_rsp.birthDay = int(time.mktime(user.birthday.timetuple()))
return user_info_rsp
@logger.catch
def CreateUser(self, request: user_pb2.CreateUserInfo, context) -> user_pb2.UserInfoResponse:
nickname = request.nickName
password = request.password
mobile = request.mobile
try:
context.set_code(grpc.StatusCode.ALREADY_EXISTS)
context.set_details("User exist")
return user_pb2.UserInfoResponse()
except DoesNotExist:
pass
user = User()
user.nick_name = nickname
user.mobile = mobile
user.password = pbkdf2_sha256.hash(password)
user.save()
return self.convert_user_to_rsp(user)
@logger.catch
def UpdateUser(self, request: user_pb2.UpdateUserInfo, context):
try:
user = User.get(User.id == request.id)
if request.nickName is not None and request.nickName != '':
user.nick_name = request.nickName
if request.gender is not None and request.gender != '':
user.gender = request.gender
if request.birthday is not None and request.birthday != 0:
user.birthday = date.fromtimestamp(request.birthday)
user.save()
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("User does not exist")
return empty_pb2.Empty()
@logger.catch
def GetUserList(self, request: user_pb2.PageInfo, context):
users = User.select()
rsp = user_pb2.UserListResponse()
rsp.total = users.count()
start = 0
per_page_numbers = 10
if request.pSize:
per_page_numbers = request.pSize
if request.pn:
start = per_page_numbers * (request.pn - 1)
users = users.limit(per_page_numbers).offset(start)
for user in users:
user_info_rsp = self.convert_user_to_rsp(user)
rsp.data.append(user_info_rsp)
return rsp
@logger.catch
def GetUserByMobile(self, request: user_pb2.MobileRequest, context):
try:
user = User.get(User.mobile == request.mobile)
user_info_rsp = self.convert_user_to_rsp(user)
return user_info_rsp
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("User does not exist")
return user_pb2.UserInfoResponse()
@logger.catch
def GetUserById(self, request: user_pb2.IdRequest, context):
try:
user = User.get(User.id == request.id)
user_info_rsp = self.convert_user_to_rsp(user)
return user_info_rsp
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("User does not exist")
return user_pb2.UserInfoResponse()
@logger.catch
def CheckPassword(self, request:user_pb2.IdRequest, context):
return user_pb2.checkResponse(success=pbkdf2_sha256.verify(request.password, request.encryptedPassword))
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,631
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/order_service/model/model.py
|
from peewee import *
from datetime import datetime
from order_service.settings import settings
class BaseModel(Model):
add_time = DateTimeField(default=datetime.now())
is_deleted = BooleanField(default=False)
update_time = DateTimeField(default=datetime.now())
def save(self, *args, **kwargs):
if self._pk is not None:
self.update_time = datetime.now()
return super().save(*args, **kwargs)
@classmethod
def delete(cls, permanently=False):
if permanently:
return super().delete()
else:
return super().update(is_deleted=True)
def delete_instance(self, permanently=False, recursive=False, delete_nullable=False):
if permanently:
return self.delete(permanently).where(self._pk_expr()).execute()
else:
self.is_deleted = True
self.save()
@classmethod
def select(cls, *fields):
return super().select(*fields).where(cls.is_deleted == False)
class Meta:
database = settings.DB
class ShoppingCart(BaseModel):
user = IntegerField()
goods = IntegerField()
nums = IntegerField()
checked = BooleanField(default=True)
class OrderInfo(BaseModel):
ORDER_STATUS = (
("TRADE_SUCCESS", "Success"),
("TRADE_CLOSED", "Closed"),
("WAIT_FOR_PAY", "Created Order"),
("TRADE_FINISHED", "Trade Complete")
)
PAY_TYPE = (
("alipay", "ALIPAY")
)
user = IntegerField()
order_sn = CharField(max_length=30, null=True, unique=True)
pay_type = CharField(choices=PAY_TYPE, default="alipay", max_length=30)
status = CharField(choices=ORDER_STATUS, default="paying", max_length=30)
trade_no = CharField(max_length=100, unique=True, null=True)
order_amount = FloatField(default=0.0)
pay_time = DateTimeField(null=True)
address = CharField(max_length=100, default="", verbose_name="收货地址")
signer_name = CharField(max_length=20, default="", verbose_name="签收人")
singer_mobile = CharField(max_length=11, verbose_name="联系电话")
post = CharField(max_length=200, default="", verbose_name="留言")
class OrderGoods(BaseModel):
order = IntegerField()
goods = IntegerField()
goods_name = CharField(max_length=20, default="")
goods_image = CharField(max_length=200, default="")
goods_price = DecimalField()
nums = IntegerField(default=0)
class OrderHistory(BaseModel):
order_id = IntegerField()
order_sn = CharField(max_length=20, default="")
user = IntegerField()
addr = CharField(max_length=200, default="")
if __name__ == "__main__":
settings.DB.create_tables([ShoppingCart, OrderGoods, OrderInfo])
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,632
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/user_service/nacos_test/nacos_test.py
|
from nacos import NacosClient
server_addr = "192.168.0.10:8848"
namespace = "f8bdaf7d-b24e-4080-bcf8-afefc8bcc659"
client = NacosClient(server_addr, namespace=namespace, username="nacos", password="nacos")
data_id = "user-srv.json"
group = "dev"
print(client.get_config(data_id, group))
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,633
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/user_service/server.py
|
import consul
import grpc
import logging
import signal
import sys
import os
import argparse
import environ
import uuid
from concurrent import futures
import requests
from loguru import logger
BASE_DIR = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, BASE_DIR)
from user_service.proto import user_pb2_grpc
from user_service.handler.user import UserServicer
from common.grpc_health.v1 import health_pb2, health_pb2_grpc
from common.grpc_health.v1 import health
from common.server import BaseServer
from user_service.settings import setting
USER_SERVICE_HOST = None
USER_SERVICE_PORT = None
CONSUL_HOST = None
CONSUL_PORT = None
SERVICE_ID = "mxshop-user-srv"
def onExit(signo, frame):
logger.info("Process Terminate")
sys.exit(0)
def read_config():
path = environ.Path(__file__) - 1
env = environ.Env()
environ.Env.read_env(path('.env'))
host = env.get_value('user_srv_host')
port = int(env.get_value('user_srv_port'))
consul_host = env.get_value('consul_server_host')
consul_port = int(env.get_value('consul_server_port'))
return host, port, consul_host, consul_port
def serve():
parser = argparse.ArgumentParser()
parser.add_argument('--ip',
nargs="?",
type=str,
default=USER_SERVICE_HOST,
help="ip")
parser.add_argument('--port',
nargs="?",
type=int,
default=USER_SERVICE_PORT,
help="port")
args = parser.parse_args()
logger.add("logs/user_service_{time}.log")
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
user_pb2_grpc.add_UserServicer_to_server(UserServicer(), server)
# 注册健康检查
health_servicer = health.HealthServicer()
health_pb2_grpc.add_HealthServicer_to_server(health_servicer, server)
server.add_insecure_port(f'[::]:{args.port}')
# 主进程退出信号监听
signal.signal(signal.SIGINT, onExit)
signal.signal(signal.SIGTERM, onExit)
logger.info("Start User Srv Service at {}:{}".format(args.ip, args.port))
server.start()
server.wait_for_termination()
class UserServiceServer(BaseServer):
SERVICE_NAME = "user-srv"
def __init__(self, host, port):
super(UserServiceServer, self).__init__()
self.SERVICE_ID = self.SERVICE_NAME + "-" + f'{str(uuid.uuid4())}'
self.SERVICE_HOST = host
self.SERVICE_PORT = port
self.CONSUL_HOST = setting.data["consul"]["host"]
self.CONSUL_PORT = setting.data["consul"]["port"]
logger.add("logs/user_service_{time}.log")
def onExit(self, signo, frame):
logger.info("User service terminate")
self.unregister()
sys.exit(0)
def read_config_from_env(self):
path = environ.Path(__file__) - 1
env = environ.Env()
environ.Env.read_env(path('.env'))
self.SERVICE_HOST = env.get_value('user_srv_host')
if self.SERVICE_PORT is None:
self.SERVICE_PORT = int(env.get_value('user_srv_port'))
self.CONSUL_HOST = env.get_value('consul_server_host')
self.CONSUL_PORT = int(env.get_value('consul_server_port'))
def register_request(self):
url = "http://{}:{}/v1/agent/service/register".format(self.CONSUL_HOST, self.CONSUL_PORT)
headers = {
"contentType": "application/json"
}
rsp = requests.put(url, headers=headers, json={
"Name": self.SERVICE_NAME,
"ID": self.SERVICE_ID,
"Tags": ["mxshop", "bobby", "imooc", "web"],
"Address": self.SERVICE_HOST,
"Port": self.SERVICE_PORT,
"Check": {
"GRPC": f"{self.SERVICE_HOST}:{self.SERVICE_PORT}",
"GRPCUseTLS": False,
"Timeout": "5s",
"Interval": "5s",
"DeregisterCriticalServiceAfter": "15s"
}
})
if rsp.status_code == 200:
print("registered success")
else:
print(f"registered failed:{rsp.status_code}")
def serve(self):
self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=40))
user_pb2_grpc.add_UserServicer_to_server(UserServicer(), self.server)
health_servicer = health.HealthServicer()
health_pb2_grpc.add_HealthServicer_to_server(health_servicer, self.server)
self.server.add_insecure_port(f'[::]:{self.SERVICE_PORT}')
signal.signal(signal.SIGINT, self.onExit)
signal.signal(signal.SIGTERM, self.onExit)
logger.info("Start User Srv Service at {}:{}".format(self.SERVICE_HOST, self.SERVICE_PORT))
self.server.start()
self.register()
self.server.wait_for_termination()
if __name__ == "__main__":
logging.basicConfig()
parser = argparse.ArgumentParser()
parser.add_argument('--host', nargs="?",
type=str,
default=setting.HOST,
help="host")
parser.add_argument('--port',
nargs="?",
type=int,
default=50052,
help="port")
args = parser.parse_args()
server = UserServiceServer(args.host, args.port)
server.serve()
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,634
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/userop_service/models/model.py
|
from peewee import *
from datetime import datetime
from userop_service.settings import settings
class BaseModel(Model):
add_time = DateTimeField(default=datetime.now())
is_deleted = BooleanField(default=False)
update_time = DateTimeField(default=datetime.now())
def save(self, *args, **kwargs):
if self._pk is not None:
self.update_time = datetime.now()
return super().save(*args, **kwargs)
@classmethod
def delete(cls, permanently=False):
if permanently:
return super().delete()
else:
return super().update(is_deleted=True)
def delete_instance(self, permanently=False, recursive=False, delete_nullable=False):
if permanently:
return self.delete(permanently).where(self._pk_expr()).execute()
else:
self.is_deleted = True
self.save()
@classmethod
def select(cls, *fields):
return super().select(*fields).where(cls.is_deleted == False)
class Meta:
database = settings.DB
class LeavingMessages(BaseModel):
MESSAGE_CHOICES = (
(1, "留言"),
(2, "投诉"),
(3, "询问"),
(4, "售后"),
(5, "求购")
)
user = IntegerField()
message_type = IntegerField(default=1, choices=MESSAGE_CHOICES)
subject = CharField(max_length=100, default="")
message = TextField(default="")
file = CharField(max_length=100, null=True)
class Address(BaseModel):
user = IntegerField()
province = CharField(max_length=100, default="", null=True)
city = CharField(max_length=100, default="", null=True)
district = CharField(max_length=100, default="")
address = CharField(max_length=100, default="", null=False)
country = CharField(max_length=20, default="CA", null=False)
signer_name = CharField(max_length=100, default="", verbose_name="签收人")
signer_mobile = CharField(max_length=11, default="", verbose_name="电话")
class UserFav(BaseModel):
user = IntegerField()
goods = IntegerField()
class Meta:
primary_key = CompositeKey('user', 'goods')
if __name__ == "__main__":
settings.DB.create_tables([LeavingMessages, Address, UserFav])
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,635
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/data_service/client/client.py
|
import grpc
from data_service.proto import data_pb2, data_pb2_grpc
class DataClient:
def __init__(self,ip, port):
channel = grpc.insecure_channel(f"{ip}:{port}")
self.data_stub = data_pb2_grpc.DataServiceStub(channel)
def GetData(self):
rsp = self.data_stub.GetData(data_pb2.DataRequest(
id=2,name="hello"
))
print(rsp.code)
print(rsp.content)
a = DataClient("192.168.0.14", "50099")
a.GetData()
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,636
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/order_service/handler/handler.py
|
import json
import grpc
import time
import opentracing
from common.grpc_interceptor.grpc_retry import RetryInterceptor
from order_service.proto import order_pb2, order_pb2_grpc
from loguru import logger
from random import Random
from datetime import datetime
from order_service.model.model import *
from google.protobuf import empty_pb2
from common.register import consul
from order_service.settings import settings
from order_service.proto import goods_pb2, goods_pb2_grpc, inventory_pb2, inventory_pb2_grpc
from rocketmq.client import Producer, TransactionStatus, TransactionMQProducer, Message, SendStatus, ConsumeStatus
def generate_order_sn(user_id):
random_ins = Random()
order_sn = f"{time.strftime('%Y%m%d%H%M%S')}{user_id}{random_ins.randint(10, 99)}"
return order_sn
def order_timeout(msg):
logger.info("超市消息接收时间 " + f"{datetime.now()}")
msg_body_str = msg.body.decode("utf-8")
msg_body = json.loads(msg_body_str)
order_sn = msg_body["orderSn"]
order = OrderInfo.get(OrderInfo.order_sn==order_sn)
with settings.DB.atomic() as txn:
try:
if order.status != "TRADE_SUCCESS":
order.status == "TRADE_CLOSED"
order.save()
msg = Message("order_reback")
msg.set_keys("mxshop")
msg.set_tags("reback")
msg.set_body(json.dumps({
"orderSn": order_sn
}))
sync_producer = Producer("order_sender")
sync_producer.set_name_server_address(f"{settings.RocketMQ_HOST}:{settings.RocketMQ_PORT}")
sync_producer.start()
ret = sync_producer.send_sync(msg)
if ret.status != SendStatus.OK:
raise Exception("发送失败")
sync_producer.shutdown()
except Exception as e:
logger.info(e)
txn.rollback()
return ConsumeStatus.RECONSUME_LATER
return ConsumeStatus.CONSUME_SUCCESS
local_execute_dict = {}
class OrderService(order_pb2_grpc.OrderServicer):
@logger.catch
def CartItemList(self, request: order_pb2.UserInfo, context):
items = ShoppingCart.select().where(ShoppingCart.user == request.id)
rsp = order_pb2.CartItemListResponse()
rsp.total = items.count()
for item in items:
item_rsp = order_pb2.ShopCartInfoResponse()
item_rsp.id = item.id
item_rsp.userId = item.user
item_rsp.goodsId = item.goods
item_rsp.nums = item.nums
items.checked = item.checked
rsp.data.append(item_rsp)
return rsp
def CreateCartItem(self, request: order_pb2.CartItemRequest, context):
existed_items = ShoppingCart.select().where(ShoppingCart.user == request.userId,
ShoppingCart.goods == request.goodsId)
if existed_items:
item = existed_items[0]
item.nums += request.nums
else:
item = ShoppingCart()
item.user = request.userId
item.goods = request.goodsId
item.nums = request.nums
item.save()
return order_pb2.ShopCartInfoResponse(id=item.id)
def UpdateCartItem(self, request, context):
try:
item = ShoppingCart.get(ShoppingCart.user == request.userId, ShoppingCart.goods == request.goodsId)
item.checked = request.checked
if request.nums:
item.nums = request.nums
item.save()
return empty_pb2()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Shopping cart does not exist")
return empty_pb2()
def DeleteCartItem(self, request, context):
try:
item = ShoppingCart.get(ShoppingCart.user == request.userId, ShoppingCart.goods == request.goodsId)
item.delete_instance()
return empty_pb2.Empty()
except DoesNotExist as e:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Shopping cart does not exist")
return empty_pb2.Empty()
def convert_order_into_response(self, order: OrderInfo) -> order_pb2.OrderInfoResponse:
order_rsp = order_pb2.OrderInfoResponse()
order_rsp.id = order.id
order_rsp.userId = order.user
order_rsp.orderSn = order.order_sn
order_rsp.payType = order.pay_type
order_rsp.status = order.status
order_rsp.post = order.post
order_rsp.total = order.order_amount
order_rsp.address = order.address
order_rsp.name = order.signer_name
order_rsp.mobile = order.singer_mobile
order_rsp.addTime = order.add_time.strftime('%Y-%m-%d %H:%M:%S')
return order_rsp
@logger.catch
def OrderList(self, request, context):
rsp = order_pb2.OrderListResponse()
orders = OrderInfo.select()
if request.userId:
orders = orders.where(OrderInfo.user == request.userId)
rsp.total = orders.count()
per_page_nums = request.pagePerNums if request.pagePerNums else 10
start = per_page_nums * (request.pages - 1) if request.pages else 0
orders = orders.limit(per_page_nums).offset(start)
for order in orders:
order_rsp = self.convert_order_into_response(order)
rsp.data.append(order_rsp)
return rsp
def OrderDetail(self, request: order_pb2.OrderRequest, context):
rsp = order_pb2.OrderInfoDetailResponse()
try:
if request.userId:
order: OrderInfo = OrderInfo.get(OrderInfo.id == request.id, OrderInfo.user == request.userId)
else:
order: OrderInfo = OrderInfo.get(OrderInfo.id == request.id)
rsp.orderInfo = self.convert_order_into_response(order)
order_goods = OrderGoods.select().where(OrderGoods.order == order.id)
for order_good in order_goods:
order_goods_rsp = order_pb2.OrderItemResponse()
order_goods_rsp.id = order_good.id
order_goods_rsp.goodsId = order_good.goods
order_goods_rsp.goodsName = order_good.goods_name
order_goods_rsp.goodsImage = order_good.goods_image
order_goods_rsp.goodsPrice = float(order_good.goods_price)
order_goods_rsp.nums = order_good.nums
rsp.data.append(order_goods_rsp)
return rsp
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Order does not exist")
return rsp
def UpdateOrderStatus(self, request, context):
OrderInfo.update(status=request.status).where(OrderInfo.order_sn == request.orderSn)
return empty_pb2.Empty()
@logger.catch
def check_callback(self, msg):
msg_body = json.loads(msg.body.decode("utf-8"))
order_sn = msg_body["orderSn"]
orders = OrderInfo.select().where(OrderInfo.order_sn==order_sn)
if orders:
return TransactionStatus.ROLLBACK
else:
return TransactionStatus.COMMIT
def local_execute(self, msg, user_args):
msg_body = json.loads(msg.body.decode("utf-8"))
order_sn = msg_body["orderSn"]
local_execute_dict[order_sn] = {}
parent_span = local_execute_dict[msg_body["parent_span_id"]]
with settings.DB.atomic() as txn:
goods_ids = []
goods_nums = {}
order_amount = 0
order_goods_list = []
tracer = opentracing.global_tracer()
with tracer.start_span("select_shopcart") as select_shopchart_span:
for cart_item in ShoppingCart.select().where(ShoppingCart.user == msg_body["userId"], ShoppingCart.checked == True):
goods_ids.append(cart_item.goods)
goods_nums[cart_item.goods] = cart_item.nums
if not goods_ids:
local_execute_dict[order_sn]["code"] = grpc.StatusCode.NOT_FOUND
local_execute_dict[order_sn]["detail"] = "No item in shopping cart"
return TransactionStatus.ROLLBACK
# query goods info from goods srv
with tracer.start_span("query_goods", child_of=parent_span) as query_goods_span:
register = consul.ConsulRegister(settings.CONSUL_HOST, settings.CONSUL_POST)
goods_srv_host, goods_srv_port = register.get_host_port(f'Service == "{settings.Goods_srv_name}"')
if not goods_srv_host or not goods_srv_port:
local_execute_dict[order_sn]["code"] = grpc.StatusCode.NOT_FOUND
local_execute_dict[order_sn]["detail"] = "Goods service not available"
return TransactionStatus.ROLLBACK
goods_channel = grpc.insecure_channel(f"{goods_srv_host}:{goods_srv_port}")
goods_stub = goods_pb2_grpc.GoodsStub(goods_channel)
goods_sell_info = []
try:
goods_rsp = goods_stub.BatchGetGoods(goods_pb2.BatchGoodsIdInfo(id=goods_ids))
for good in goods_rsp.data:
order_amount += good.shopPrice * goods_nums[good.id]
order_goods = OrderGoods(goods=good.id, goods_name=good.name, goods_image=good.goodsFrontImage,
goods_price=good.shopPrice, nums=goods_nums[good.id])
order_goods_list.append(order_goods)
goods_sell_info.append(inventory_pb2.GoodsInvInfo(goodsId=good.id, num=goods_nums[good.id]))
except grpc.RpcError as e:
local_execute_dict[order_sn]["code"] = grpc.StatusCode.INTERNAL
local_execute_dict[order_sn]["detail"] = str(e)
return TransactionStatus.ROLLBACK
# prepare half message
with tracer.start_span("query_inv", child_of=parent_span) as query_inv_span:
inventory_host, inventory_port = register.get_host_port(f'Service == "{settings.Inventory_srv_name}"')
if not inventory_host or not inventory_port:
local_execute_dict[order_sn]["code"] = grpc.StatusCode.INTERNA
local_execute_dict[order_sn]["detail"] = "Inventory service not available"
return TransactionStatus.ROLLBACK
inventory_channel = grpc.insecure_channel(f"{inventory_host}:{inventory_port}")
inventory_channel = grpc.intercept_channel(inventory_channel, RetryInterceptor)
inv_stub = inventory_pb2_grpc.InventoryStub(inventory_channel)
try:
inv_stub.Sell(inventory_pb2.SellInfo(goodsInfo=goods_sell_info, orderSn=order_sn))
except grpc.RpcError as e:
local_execute_dict[order_sn]["code"] = grpc.StatusCode.INTERNAL
local_execute_dict[order_sn]["detail"] = str(e)
err_code = e.code()
if err_code == grpc.StatusCode.UNKNOWN or grpc.StatusCode.DEADLINE_EXCEEDED:
return TransactionStatus.COMMIT
else:
return TransactionStatus.ROLLBACK
with tracer.start_span("insert_order", child_of=parent_span) as insert_order_span:
try:
order = OrderInfo()
order.user = msg_body["userId"]
order.order_sn = order_sn
order.order_amount = order_amount
order.address = msg_body["address"]
order.signer_name = msg_body["name"]
order.singer_mobile = msg_body["mobile"]
order.post = msg_body["post"]
order.save()
for order_goods in order_goods_list:
order_goods.order = order.id
OrderGoods.bulk_create(order_goods_list)
ShoppingCart.delete().where(ShoppingCart.user == msg_body["userId"], ShoppingCart.checked == True).execute()
local_execute_dict[order_sn] = {
"code": grpc.StatusCode.OK,
"detail": "Create order succeeded",
"order": {
"id": order.id,
"orderSn": order_sn,
"total": order.order_amount
}
}
#发送延时消息
msg = Message("order_timeout")
msg.set_delay_time_level(16)
msg.set_keys("imooc")
msg.set_tags("cancel")
msg.set_body(json.dumps({
"orderSn": order_sn
}))
sync_producer = Producer("cancel")
sync_producer.set_name_server_address(f"{settings.RocketMQ_HOST}:{settings.RocketMQ_PORT}")
sync_producer.start()
ret = sync_producer.send_sync(msg)
if ret.status != SendStatus.OK:
raise Exception("延时消息发送失败")
logger.info("发送延时消息时间" + datetime.now())
sync_producer.shutdown()
except Exception as e:
txn.rollback()
local_execute_dict[order_sn]["code"] = grpc.StatusCode.INTERNA
local_execute_dict[order_sn]["detail"] = str(e)
return TransactionStatus.COMMIT
return TransactionStatus.ROLLBACK
def CreateOrder(self, request, context):
parent_span = context.get_active_span()
local_execute_dict[parent_span.context.span_id] = parent_span
producer = TransactionMQProducer(group_id="mxshop", checker_callback=self.check_callback)
producer.set_name_server_address(f"{settings.RocketMQ_HOST}:{settings.RocketMQ_PORT}")
producer.start()
msg = Message("order_reback")
msg.set_keys("mxshop")
msg.set_tags("order")
order_sn = generate_order_sn(request.userId)
msg_body = {
'orderSn': order_sn,
"userId": request.userId,
"address": request.address,
"name": request.name,
"mobile": request.mobile,
"post": request.post,
"parent_span_id": parent_span.context.span_id
}
msg.set_body(json.dumps(msg_body))
ret = producer.send_message_in_transaction(msg, self.local_execute, user_args=None)
logger.info(f"Send status: {ret.status}, id: {ret.msg_id}")
if ret.status != SendStatus.OK:
context.set_code(grpc.StatusCode.INTERNAL)
context.set_details("Create order failed")
return order_pb2.OrderInfoResponse()
while True:
if order_sn in local_execute_dict:
context.set_code(local_execute_dict[order_sn]["code"])
context.set_details(local_execute_dict[order_sn]["detail"])
producer.shutdown()
if local_execute_dict[order_sn]["code"] == grpc.StatusCode.OK:
return order_pb2.OrderInfoResponse(id=local_execute_dict[order_sn]["order"]["id"],
orderSn=order_sn,
total=local_execute_dict[order_sn]["order"]["total"])
else:
return order_pb2.OrderInfoResponse()
time.sleep(0.1)
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,637
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/user_service/client.py
|
import grpc
from user_service.proto import user_pb2, user_pb2_grpc
class UserTest:
def __init__(self):
channel = grpc.insecure_channel("127.0.0.1:50058")
self.stub = user_pb2_grpc.UserStub(channel)
def user_list(self):
rsp :user_pb2.UserListResponse = self.stub.GetUserList(user_pb2.PageInfo())
print(rsp.total)
for user in rsp.data:
print(user.mobile, user.id, user.birthDay)
def user_by_id(self):
rsp : user_pb2.UserInfoResponse = self.stub.GetUserById(user_pb2.IdRequest(id=1))
print(rsp.password)
def user_by_mobile(self):
pass
def create_user(self):
rsp : user_pb2.UserInfoResponse = self.stub.CreateUser(user_pb2.CreateUserInfo(
nickName="ok",
mobile="12222222",
password="123456"
))
print(rsp.id)
if __name__ == "__main__":
user = UserTest()
user.create_user()
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,638
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/userop_service/handler/user_fav.py
|
from typing import List
import grpc
from loguru import logger
from peewee import DoesNotExist
from userop_service.models.model import UserFav
from userop_service.proto import userfav_pb2, userfav_pb2_grpc
from google.protobuf import empty_pb2
class UserFavServicer(userfav_pb2_grpc.UserFavServicer):
@logger.catch
def GetFavList(self, request, context):
rsp = userfav_pb2.UserFavListResponse()
user_favs: List[UserFav] = UserFav.select()
if request.userId:
user_favs = user_favs.where(UserFav.user==request.userId)
if request.goodsId:
user_favs = user_favs.where(UserFav.goods==request.goodsId)
rsp.total == user_favs.count()
for user_fav in user_favs:
user_fav_rsp = userfav_pb2.UserFavResponse()
user_fav_rsp.userId = user_fav.user
user_fav_rsp.goodsId = user_fav.goods
rsp.data.append(user_fav_rsp)
return rsp
@logger.catch
def AddUserFav(self, request, context):
user_fav = UserFav()
user_fav.user = request.userId
user_fav.goods = request.goodsId
user_fav.save(force_insert=True)
return empty_pb2.Empty()
def DeleteUserFav(self, request, context):
try:
user_fav = UserFav.get(UserFav.user == request.userId, UserFav.goods == request.goodsId)
user_fav.delete_instance(permanently=True)
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('记录不存在')
return empty_pb2.Empty()
def GetUserFavDetail(self, request, context):
rsp = userfav_pb2.UserFavExist()
try:
UserFav.get(UserFav.user==request.userId, UserFav.goods==request.goodsId)
rsp.exist = True
return rsp
except:
rsp.exist = False
return rsp
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,639
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/order_service/test/order.py
|
import consul
import grpc
from order_service.proto import order_pb2_grpc, order_pb2
from order_service.settings import settings
class OrderTest:
def __init__(self):
c = consul.Consul(host=settings.CONSUL_HOST, port=settings.CONSUL_POST)
services = c.agent.services()
ip, port = None, None
for key, value in services.items():
if value["Service"] == settings.Service_name:
ip = value['Address']
port = value['Port']
break
if not ip or not port:
raise Exception()
channel = grpc.insecure_channel(f"{ip}:{port}")
self.order_stub = order_pb2_grpc.OrderStub(channel)
def create_cart_item(self):
rsp = self.order_stub.CreateCartItem(order_pb2.CartItemRequest(
goodsId=421, userId=2, nums=3
))
print(rsp)
def create_order(self):
rsp = self.order_stub.CreateOrder(
order_pb2.OrderRequest(userId=1, address="85 wood street", mobile="4332221111",
name="bobby", post="")
)
print(rsp)
def cart_list(self):
rsp = self.order_stub.CartItemList(order_pb2.UserInfo(id=2))
print(rsp)
def order_list(self):
rsp = self.order_stub.OrderList(order_pb2.OrderFilterRequest(userId=1))
print(rsp)
if __name__ == "__main__":
order = OrderTest()
order.cart_list()
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,640
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/inventory_service/model/models.py
|
from peewee import *
from datetime import datetime
from inventory_service.settings import settings
from playhouse.mysql_ext import JSONField
class BaseModel(Model):
add_time = DateTimeField(default=datetime.now)
is_deleted = BooleanField(default=False)
update_time = DateTimeField(default=datetime.now)
def save(self, *args, **kwargs):
# 判断这是一个新添加的数据还是更新的数据
if self._pk is not None:
# 这是一个新数据
self.update_time = datetime.now()
return super().save(*args, **kwargs)
@classmethod
def delete(cls, permanently=False): # permanently表示是否永久删除
if permanently:
return super().delete()
else:
return super().update(is_deleted=True)
def delete_instance(self, permanently=False, recursive=False, delete_nullable=False):
if permanently:
return self.delete(permanently).where(self._pk_expr()).execute()
else:
self.is_deleted = True
self.save()
@classmethod
def select(cls, *fields):
return super().select(*fields).where(cls.is_deleted == False)
class Meta:
database = settings.DB
class Inventory(BaseModel):
goods = IntegerField(unique=True)
stocks = IntegerField(default=0)
version = IntegerField(default=0)
class InventoryHistory(BaseModel):
order_sn = CharField(max_length=20, unique=True)
order_inv_detail = CharField(max_length=200)
status = IntegerField(choices=((1, "DEDUCED"), (2, "RETURNED")), default=1, verbose_name="出库状态")
if __name__ == "__main__":
settings.DB.create_tables([InventoryHistory])
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,641
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/goods_service/settings/settings.py
|
import json
import environ
import nacos
from playhouse.pool import PooledMySQLDatabase
from playhouse.shortcuts import ReconnectMixin
from loguru import logger
class ReconnectMySQLDataBase(PooledMySQLDatabase, ReconnectMixin):
pass
"""
MYSQL_DB = "mxshop_user_srv"
MYSQL_HOST = "192.168.0.10"
MYSQL_PORT = 3306
MYSQL_USER = "root"
MYSQL_PASSWORD = "31415926"
"""
path = environ.Path(__file__) - 2
env = environ.Env()
environ.Env.read_env(path('.env'))
NACOS = {
"Host": env.get_value("nacos_host"),
"Port": env.get_value("nacos_port"),
"NameSpace": env.get_value("nacos_namespace"),
"User": "nacos",
"Password": "nacos",
"DataId": env.get_value("nacos_dataId"),
"Group": env.get_value("nacos_group")
}
client = nacos.NacosClient(f"{NACOS['Host']}:{NACOS['Port']}", namespace=NACOS['NameSpace'],
username='nacos', password='nacos')
data = json.loads(client.get_config(NACOS["DataId"], NACOS["Group"]))
mysql_config = data['mysql']
DB = ReconnectMySQLDataBase(database=mysql_config['db'], host=mysql_config['host'], port=mysql_config['port'], user=mysql_config['user'],
password=mysql_config['password'])
HOST = data['host']
logger.info("Read config from nacos " + f"{NACOS['Host']}:{NACOS['Port']}")
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,642
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/goods_service/handler/handler.py
|
import json
import grpc
import time
from goods_service.proto import goods_pb2, goods_pb2_grpc
from goods_service.model.models import *
from google.protobuf import empty_pb2
from loguru import logger
class GoodsServices(goods_pb2_grpc.GoodsServicer):
def category_model_to_dic(self, category: Category) -> dict:
res = {
"id": category.id,
"name": category.name,
"level": category.level,
"parent": category.parent_category_id,
"is_tab": category.is_tab
}
return res
def convert_model_to_message(self, goods: BaseModel) -> goods_pb2.GoodsInfoResponse:
info_rsp = goods_pb2.GoodsInfoResponse()
info_rsp.id = goods.id
info_rsp.categoryId = goods.category_id
info_rsp.name = goods.name
info_rsp.goodsSn = goods.goods_sn
info_rsp.clickNum = goods.click_num
info_rsp.soldNum = goods.sold_num
info_rsp.favNum = goods.fav_num
info_rsp.marketPrice = goods.market_price
info_rsp.shopPrice = goods.shop_price
info_rsp.goodsBrief = goods.goods_brief
info_rsp.shipFree = goods.ship_free
info_rsp.goodsFrontImage = goods.goods_front_image
info_rsp.isNew = goods.is_new
info_rsp.descImages.extend(goods.desc_images)
info_rsp.images.extend(goods.desc_images)
info_rsp.isHot = goods.is_hot
info_rsp.onSale = goods.on_sale
info_rsp.category.id = goods.category.id
info_rsp.category.name = goods.category.name
info_rsp.brand.id = goods.brand.id
info_rsp.brand.name = goods.brand.name
info_rsp.brand.logo = goods.brand.logo
return info_rsp
@logger.catch
def GoodsList(self, request: goods_pb2.GoodsFilterRequest, context) -> goods_pb2.GoodsListResponse:
rsp = goods_pb2.GoodsListResponse()
goods: BaseModel = Goods.select()
if request.keyWords:
goods = goods.where(Goods.name.contains(request.keyWords))
if request.isHot:
goods = goods.filter(Goods.is_hot == True)
if request.isNew:
goods = goods.filter(Goods.is_new == True)
if request.priceMin:
goods = goods.filter(Goods.shop_price >= request.priceMin)
if request.priceMax:
goods = goods.filter(Goods.shop_price <= request.priceMax)
if request.brand:
goods = goods.filter(Goods.brand_id == request.brand)
if request.topCategory:
try:
ids = []
category = Category.get(Category.id == request.topCategory)
level = category.level
if level == 1:
c2 = Category.alias()
categorys = Category.select().where(Category.parent_category_id.in_(
c2.select(c2.id).where(c2.parent_category_id == request.topCategory)
))
for category in categorys:
ids.append(category.id)
elif level == 2:
categorys = Category.select().where(Category.parent_category_id == request.topCategory)
for category in categorys:
ids.append(category.id)
elif level == 3:
ids.append(request.topCategory)
goods = goods.where(Goods.category_id.in_(ids))
except Exception as e:
pass
start, per_page_nums = 0, 10
if request.pagePerNums:
per_page_nums = request.pagePerNums
if request.pages:
start = per_page_nums * (request.pages - 1)
rsp.total = goods.count()
goods = goods.limit(per_page_nums).offset(start)
for good in goods:
rsp.data.append(self.convert_model_to_message(good))
return rsp
@logger.catch
def GetGoodsDetail(self, request: goods_pb2.GoodInfoRequest, context):
try:
goods = Goods.get(Goods.id == request.id)
goods.click_num += 1
goods.save()
return self.convert_model_to_message(goods)
except:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Goods Does not exist")
return goods_pb2.GoodsInfoResponse()
@logger.catch
def BatchGetGoods(self, request: goods_pb2.BatchGoodsIdInfo, context) -> goods_pb2.GoodsListResponse:
rsp = goods_pb2.GoodsListResponse()
ids = list(request.id)
goods = Goods.select().where(Goods.id.in_(ids))
rsp.total = goods.count()
for good in goods:
rsp.data.append(self.convert_model_to_message(good))
return rsp
@logger.catch
def CreateGoods(self, request: goods_pb2.CreateGoodsInfo, context) -> goods_pb2.GoodsInfoResponse:
try:
category = Category.get(Category.id == request.categoryId)
except DoesNotExist as e:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Category does not exist")
return goods_pb2.GoodsInfoResponse()
try:
brand = Brands.get(Brands.id == request.brandId)
except DoesNotExist as e:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Brand does not exist")
return goods_pb2.GoodsInfoResponse()
goods = Goods()
goods.brand = brand
goods.category = category
goods.name = request.name
goods.goods_sn = request.goodsSn
goods.market_price = request.marketPrice
goods.shop_price = request.shopPrice
goods.goods_brief = request.goodsBrief
goods.ship_free = request.shipFree
goods.images = list(request.images)
goods.desc_images = list(request.descImages)
goods.goods_front_image = request.goodsFrontImage
goods.is_new = request.isNew
goods.is_hot = request.isHot
goods.on_sale = request.onSale
goods.save()
return self.convert_model_to_message(goods)
@logger.catch
def DeleteGoods(self, request: goods_pb2.DeleteGoodsInfo, context):
try:
goods: Goods = Goods.get(Goods.id == request.id)
goods.delete_instance()
return empty_pb2.Empty()
except DoesNotExist as e:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Good does not exist")
return empty_pb2.Empty()
except Exception as e:
context.set_code(grpc.StatusCode.INTERNAL)
context.set_details(str(e))
return empty_pb2.Empty()
@logger.catch
def UpdateGoods(self, request: goods_pb2.CreateGoodsInfo, context):
if not request.id:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Empty Goods id")
return empty_pb2.Empty()
category, brand = None, None
if request.categoryId:
try:
category = Category.get(Category.id == request.categoryId)
except DoesNotExist as e:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Category does not exist")
return goods_pb2.GoodsInfoResponse()
if request.brandId:
try:
brand = Brands.get(Brands.id == request.brandId)
except DoesNotExist as e:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Brand does not exist")
return goods_pb2.GoodsInfoResponse()
try:
goods = Goods.get(Goods.id == request.id)
except DoesNotExist as e:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Goods does not exist")
return goods_pb2.GoodsInfoResponse()
if brand:
goods.brand = brand
if category:
goods.category = category
goods.name = request.name
goods.goods_sn = request.goodsSn
goods.market_price = request.marketPrice
goods.shop_price = request.shopPrice
goods.goods_brief = request.goodsBrief
goods.ship_free = request.shipFree
goods.images = list(request.images)
goods.desc_images = list(request.descImages)
goods.goods_front_image = request.goodsFrontImage
goods.is_new = request.isNew
goods.is_hot = request.isHot
goods.on_sale = request.onSale
goods.save()
return self.convert_model_to_message(goods)
@logger.catch
def GetAllCategorysList(self, request, context):
rsp = goods_pb2.CategoryListResponse()
categories = Category.select()
rsp.total = categories.count()
level1, level2, level3 = [], [], []
for category in categories:
category_rsp = goods_pb2.CategoryInfoResponse()
category_rsp.id = category.id
category_rsp.name = category.name
if category.parent_category_id:
category_rsp.parentCategory = category.parent_category_id
category_rsp.level = category.level
category_rsp.isTab = category.is_tab
rsp.data.append(category_rsp)
if category.level == 1:
level1.append(self.category_model_to_dic(category))
elif category.level == 2:
level2.append(self.category_model_to_dic(category))
elif category.level == 3:
level3.append(self.category_model_to_dic(category))
for data3 in level3:
for data2 in level2:
if data3["parent"] == data2["id"]:
if "sub_category" not in data2:
data2["sub_category"] = [data3]
else:
data2["sub_category"].append(data3)
for data2 in level2:
for data1 in level1:
if data2["parent"] == data1["id"]:
if "sub_category" not in data1:
data1["sub_category"] = [data2]
else:
data1["sub_category"].append(data2)
rsp.jsonData = json.dumps(level1)
return rsp
def GetSubCategory(self, request, context):
category_list_rsp = goods_pb2.SubCategoryListResponse()
try:
category_info = Category.get(Category.id == request.id)
category_list_rsp.info.id = category_info.id
category_list_rsp.info.name = category_info.name
category_list_rsp.info.level = category_info.level
category_list_rsp.info.isTab = category_info.is_tab
if category_info.parent_category:
category_list_rsp.info.parentCategory = category_info.parent_category_id
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Category does not exist')
return goods_pb2.SubCategoryListResponse()
categorys = Category.select().where(Category.parent_category == request.id)
category_list_rsp.total = categorys.count()
for category in categorys:
category_rsp = goods_pb2.CategoryInfoResponse()
category_rsp.id = category.id
category_rsp.name = category.name
if category_info.parent_category:
category_rsp.parentCategory = category_info.parent_category_id
category_rsp.level = category.level
category_rsp.isTab = category.is_tab
category_list_rsp.subCategorys.append(category_rsp)
return category_list_rsp
def CreateCategory(self, request, context):
try:
category = Category()
category.name = request.name
if request.level != 1:
category.parent_category = request.parentCategory
category.level = request.level
category.is_tab = request.isTab
category.save()
category_rsp = goods_pb2.CategoryInfoResponse()
category_rsp.id = category.id
category_rsp.name = category.name
if category.parent_category:
category_rsp.parentCategory = category.parent_category.id
category_rsp.level = category.level
category_rsp.isTab = category.is_tab
except Exception as e:
context.set_code(grpc.StatusCode.INTERNAL)
context.set_details(str(e))
return goods_pb2.CategoryInfoResponse()
return category_rsp
def DeleteCategory(self, request, context):
try:
category = Category.get(request.id)
category.delete_instance()
# TODO 删除响应的category下的商品
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Does not exist')
return empty_pb2.Empty()
def UpdateCategory(self, request, context):
try:
category = Category.get(request.id)
if request.name:
category.name = request.name
if request.parentCategory:
category.parent_category = request.parentCategory
if request.level:
category.level = request.level
if request.isTab:
category.is_tab = request.isTab
category.save()
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Does not exist')
return empty_pb2.Empty()
@logger.catch
def BannerList(self, request: empty_pb2.Empty, context):
# 获取分类列表
rsp = goods_pb2.BannerListResponse()
banners = Banner.select()
rsp.total = banners.count()
for banner in banners:
banner_rsp = goods_pb2.BannerResponse()
banner_rsp.id = banner.id
banner_rsp.image = banner.image
banner_rsp.index = banner.index
banner_rsp.url = banner.url
rsp.data.append(banner_rsp)
return rsp
@logger.catch
def CreateBanner(self, request: goods_pb2.BannerRequest, context):
banner = Banner()
banner.image = request.image
banner.index = request.index
banner.url = request.url
banner.save()
banner_rsp = goods_pb2.BannerResponse()
banner_rsp.id = banner.id
banner_rsp.image = banner.image
banner_rsp.url = banner.url
return banner_rsp
@logger.catch
def DeleteBanner(self, request: goods_pb2.BannerRequest, context):
try:
banner = Banner.get(request.id)
banner.delete_instance()
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Banner does not exist')
return empty_pb2.Empty()
@logger.catch
def UpdateBanner(self, request: goods_pb2.BannerRequest, context):
try:
banner = Banner.get(request.id)
if request.image:
banner.image = request.image
if request.index:
banner.index = request.index
if request.url:
banner.url = request.url
banner.save()
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Banner does not exist')
return empty_pb2.Empty()
# 品牌相关的接口
@logger.catch
def BrandList(self, request: empty_pb2.Empty, context):
# 获取品牌列表
start, per_page = 0, 10
if request.pagePerNums:
per_page = request.pagePerNums
if request.pages:
start = per_page * (request.pages-1)
rsp = goods_pb2.BrandListResponse()
brands = Brands.select()
rsp.total = brands.count()
brands = brands.limit(per_page).offset(start)
for brand in brands:
brand_rsp = goods_pb2.BrandInfoResponse()
brand_rsp.id = brand.id
brand_rsp.name = brand.name
brand_rsp.logo = brand.logo
rsp.data.append(brand_rsp)
return rsp
@logger.catch
def CreateBrand(self, request: goods_pb2.BrandRequest, context):
brands = Brands.select().where(Brands.name == request.name)
if brands:
context.set_code(grpc.StatusCode.ALREADY_EXISTS)
context.set_details('Brand Already Exists')
return goods_pb2.BrandInfoResponse()
brand = Brands()
brand.name = request.name
brand.logo = request.logo
brand.save()
rsp = goods_pb2.BrandInfoResponse()
rsp.id = brand.id
rsp.name = brand.name
rsp.logo = brand.logo
return rsp
@logger.catch
def DeleteBrand(self, request: goods_pb2.BrandRequest, context):
try:
brand = Brands.get(request.id)
brand.delete_instance()
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Record does not exist')
return empty_pb2.Empty()
@logger.catch
def UpdateBrand(self, request: goods_pb2.BrandRequest, context):
try:
brand = Brands.get(request.id)
if request.name:
brand.name = request.name
if request.logo:
brand.logo = request.logo
brand.save()
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Record does not exist')
return empty_pb2.Empty()
@logger.catch
def CategoryBrandList(self, request: empty_pb2.Empty, context):
# 获取品牌分类列表
rsp = goods_pb2.CategoryBrandListResponse()
category_brands = GoodsCategoryBrand.select()
# 分页
start = 0
per_page_nums = 10
if request.pagePerNums:
per_page_nums = request.PagePerNums
if request.pages:
start = per_page_nums * (request.pages - 1)
category_brands = category_brands.limit(per_page_nums).offset(start)
rsp.total = category_brands.count()
for category_brand in category_brands:
category_brand_rsp = goods_pb2.CategoryBrandResponse()
category_brand_rsp.id = category_brand.id
category_brand_rsp.brand.id = category_brand.brand.id
category_brand_rsp.brand.name = category_brand.brand.name
category_brand_rsp.brand.logo = category_brand.brand.logo
category_brand_rsp.category.id = category_brand.category.id
category_brand_rsp.category.name = category_brand.category.name
category_brand_rsp.category.parentCategory = category_brand.category.parent_category_id
category_brand_rsp.category.level = category_brand.category.level
category_brand_rsp.category.isTab = category_brand.category.is_tab
rsp.data.append(category_brand_rsp)
return rsp
@logger.catch
def GetCategoryBrandList(self, request, context):
# 获取某一个分类的所有品牌
rsp = goods_pb2.BrandListResponse()
try:
category = Category.get(Category.id == request.id)
category_brands = GoodsCategoryBrand.select().where(GoodsCategoryBrand.category == category)
rsp.total = category_brands.count()
for category_brand in category_brands:
brand_rsp = goods_pb2.BrandInfoResponse()
brand_rsp.id = category_brand.brand.id
brand_rsp.name = category_brand.brand.name
brand_rsp.logo = category_brand.brand.logo
rsp.data.append(brand_rsp)
except DoesNotExist as e:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Record does not exist')
return rsp
return rsp
@logger.catch
def CreateCategoryBrand(self, request: goods_pb2.CategoryBrandRequest, context):
category_brand = GoodsCategoryBrand()
try:
brand = Brands.get(request.brandId)
category_brand.brand = brand
category = Category.get(request.categoryId)
category_brand.category = category
category_brand.save()
rsp = goods_pb2.CategoryBrandResponse()
rsp.id = category_brand.id # 是另外一种思路
return rsp
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Record does not exist')
return goods_pb2.CategoryBrandResponse()
except Exception as e:
context.set_code(grpc.StatusCode.INTERNAL)
context.set_details('Internal Server Error')
return goods_pb2.CategoryBrandResponse()
@logger.catch
def DeleteCategoryBrand(self, request: goods_pb2.CategoryBrandRequest, context):
try:
category_brand = GoodsCategoryBrand.get(request.id)
category_brand.delete_instance()
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Record does not exist')
return empty_pb2.Empty()
@logger.catch
def UpdateCategoryBrand(self, request: goods_pb2.CategoryBrandRequest, context):
try:
category_brand = GoodsCategoryBrand.get(request.id)
brand = Brands.get(request.brandId)
category_brand.brand = brand
category = Category.get(request.categoryId)
category_brand.category = category
category_brand.save()
return empty_pb2.Empty()
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details('Record does not exist')
return empty_pb2.Empty()
except Exception as e:
context.set_code(grpc.StatusCode.INTERNAL)
context.set_details('Internal server error')
return empty_pb2.Empty()
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,643
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/common/server.py
|
import consul
import requests
from loguru import logger
class BaseServer:
SERVICE_HOST = None
SERVICE_PORT = None
CONSUL_HOST = None
CONSUL_PORT = None
SERVICE_NAME = None
SERVICE_ID = None
server = None
consul = None
check = None
def onExit(self, signo, frame):
pass
def read_config(self):
pass
def serve(self):
raise NotImplementedError
def register(self):
self.consul = consul.Consul(host=self.CONSUL_HOST, port=self.CONSUL_PORT)
if self.check is None:
check = {
"GRPC": f"{self.SERVICE_HOST}:{self.SERVICE_PORT}",
"GRPCUseTLS": False,
"Timeout": "5s",
"Interval": "5s",
"DeregisterCriticalServiceAfter": "15s"
}
else:
check = self.check
rsp: bool = self.consul.agent.service.register(name=self.SERVICE_NAME, service_id=self.SERVICE_ID,
address=self.SERVICE_HOST, port=self.SERVICE_PORT,
tags=["mxshop"], check=check)
if rsp:
logger.info('{} Registered at consul {}:{}'.format(self.SERVICE_NAME, self.CONSUL_HOST, self.CONSUL_PORT))
else:
raise Exception('Failed to registered at consul ' + f"{self.CONSUL_HOST}:{self.CONSUL_PORT}")
def unregister(self):
if self.consul is not None:
logger.info('Unregister from consul {}:{}'.format(self.CONSUL_HOST, self.CONSUL_PORT))
self.consul.agent.service.deregister(self.SERVICE_ID)
def get_all_service(self):
return self.consul.Agent.services()
def filter_service(self, filter: str):
url = f"{self.CONSUL_HOST}:{self.CONSUL_PORT}/v1/agent/services"
params = {
"filter": f'Service=="{filter}"'
}
return requests.get(url, params=params).json()
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,644
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/inventory_service/handler/handler.py
|
import json
import grpc
from inventory_service.proto import inventory_pb2, inventory_pb2_grpc
from inventory_service.model.models import *
from google.protobuf import empty_pb2
from loguru import logger
from common.lock.redis_lock import Lock
from rocketmq.client import ConsumeStatus
def reback_inv(msg):
#通过ordersn 确定库存归还
msg_body_str = msg.body.decode("utf-8")
logger.info(msg_body_str)
msg_body = json.loads(msg_body_str)
order_sn = msg_body["orderSn"]
with settings.DB.atomic() as txn:
try:
order_inv = InventoryHistory.get(InventoryHistory.order_sn==order_sn, InventoryHistory.status==1)
inv_details = json.loads(order_inv.order_inv_detail)
for item in inv_details:
goods_id = item["goods_id"]
num = item["num"]
Inventory.update(stocks=Inventory.stocks+num).where(Inventory.goods==goods_id).execute()
order_inv.status = 2
order_inv.save()
return ConsumeStatus.CONSUME_SUCCESS
except DoesNotExist as e:
return ConsumeStatus.CONSUME_SUCCESS
except Exception as e:
txn.rollback()
return ConsumeStatus.RECONSUME_LATER
class InventoryService(inventory_pb2_grpc.InventoryServicer):
@logger.catch
def SetInv(self, request: inventory_pb2.GoodsInvInfo, context):
force_insert = False
goods_id = request.goodsId
num = request.num
invs = Inventory.select().where(Inventory.goods==goods_id)
if not invs:
inv = Inventory()
inv.goods = goods_id
force_insert = True
else:
inv = invs[0]
inv.stocks = num
inv.save(force_insert=force_insert)
return empty_pb2.Empty()
@logger.catch
def InvDetail(self, request, context):
try:
inv = Inventory.get(Inventory.goods==request.goodsId)
return inventory_pb2.GoodsInvInfo(goodsId=inv.goods, num=inv.stocks)
except DoesNotExist:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Inventory not found")
return inventory_pb2.GoodsInvInfo()
@logger.catch
def Sell(self, request: inventory_pb2.SellInfo, context):
inv_history = InventoryHistory(order_sn=request.orderSn)
inv_detail = []
with settings.DB.atomic() as txn:
for item in request.goodsInfo:
lock = Lock(settings.Redis_client, f"lock:goods_{item.goodsId}", auto_renewal=True, expire=10)
lock.acquire()
try:
goods_inv = Inventory.get(Inventory.goods==item.goodsId)
except DoesNotExist:
txn.rollback()
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details("Not found")
return empty_pb2.Empty()
if goods_inv.stocks < item.num:
txn.rollback()
context.set_code(grpc.StatusCode.RESOURCE_EXHAUSTED)
context.set_details(f"Inventory is not enough for goods:{item.goodsId}")
return empty_pb2.Empty()
else:
inv_detail.append({
"goods_id": item.goodsId,
"num": item.num,
})
goods_inv.stocks -= item.num
goods_inv.save()
lock.release()
inv_history.order_inv_detail = json.dumps(inv_detail)
inv_history.save()
return empty_pb2.Empty()
@logger.catch
def Reback(self, request, context):
with settings.DB.atomic() as txn:
for item in request.goodsInfo:
lock = Lock(settings.Redis_client, f"lock:goods_{item.goodsId}", auto_renewal=True, expire=10)
lock.acquire()
try:
goods_inv = Inventory.get(Inventory.goods == item.goodsId)
except DoesNotExist as e:
txn.rollback() # 事务回滚
context.set_code(grpc.StatusCode.NOT_FOUND)
return empty_pb2.Empty()
goods_inv.stocks += item.num
goods_inv.save()
lock.release()
return empty_pb2.Empty()
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,725,645
|
birkh8792/microserviceshop_py
|
refs/heads/master
|
/user_service/model/models.py
|
from peewee import *
from user_service.settings import setting
class BaseModel(Model):
class Meta:
database = setting.DB
GENDER_CHOICES = (
("female", "Female"),
("male", "Male"),
("unknown", "Unknown")
)
ROLE_CHOICES = (
(1, "User"),
(2, "Admin")
)
class User(BaseModel):
mobile = CharField(max_length=11, index=True, unique=True, verbose_name="Phone Number")
password = CharField(max_length=200, verbose_name="Password")
nick_name = CharField(max_length=20, verbose_name="Username", null=True)
head_url = CharField(max_length=200, null=True, verbose_name="Avatar")
birthday = DateField(null=True)
address = CharField(max_length=200, null=True)
gender = CharField(max_length=6, null=True, choices=GENDER_CHOICES)
role = IntegerField(default=1, choices=ROLE_CHOICES)
|
{"/goods_service/handler/handler.py": ["/goods_service/model/models.py"], "/order_service/server.py": ["/order_service/handler/handler.py", "/common/server.py"], "/userop_service/server.py": ["/userop_service/handler/user_fav.py", "/common/server.py"], "/user_service/handler/user.py": ["/user_service/model/models.py"], "/user_service/server.py": ["/user_service/handler/user.py", "/common/server.py"], "/order_service/handler/handler.py": ["/order_service/model/model.py"], "/userop_service/handler/user_fav.py": ["/userop_service/models/model.py"], "/inventory_service/handler/handler.py": ["/inventory_service/model/models.py"]}
|
28,766,776
|
subash423/learnGit
|
refs/heads/master
|
/GooglePatentsScraper.py
|
import requests
def scraper(keywords, N=20):
pages=N//10
if N%10!=0: pages+=1
output = []
keywords = keywords.replace(" ", "%2B").replace("/", "%252f")
# print(keywords)
try:
for page_no in range(pages):
url = "https://patents.google.com/xhr/query?url=q%3D{}%26oq%3D{}%26page%3D{}&exp=".format(
keywords, keywords, page_no)
resp = requests.get(url)
json_data = resp.json()
patents = json_data["results"]["cluster"][0]["result"]
if page_no == pages-1:
if N % 10 == 0:
n = 10
else:
n = N % 10
else:
n = 10
for i in range(n):
# Title
title = patents[i]["patent"]["title"]
title = title.strip().replace("<b>", "").replace("</b>", "")
# print(title)
# Patent no.
pat = patents[i]["patent"]["publication_number"]
# print(pat)
output.append((pat, title))
except:
pass
#print("Length = ", len(output))
return output
#print(scraper("gps", 34))
|
{"/main.py": ["/GooglePatentsScraper.py"]}
|
28,766,777
|
subash423/learnGit
|
refs/heads/master
|
/main.py
|
from GooglePatentsScraper import scraper
test_cases = [
("(TANK) AND ((FREQUENCY OR CYCLE) NEAR/4 (CHANG* OR VARIABLE OR VARY* OR CHANGE OR INCREASE \
OR DECREASE OR LIGHT OR HEAVY OR FULL OR BIG* OR SMALL*))/ AND ((CHANGE OR VARIABLE OR CHANG* \
OR INCREASE OR DECREASE OR LIGHT OR HEAVY OR FULL OR BIG* OR SMALL*) 5D (LOAD)) AND \
((POWER 4D (CONVERT*)) OR BOOST OR BUCK OR SMPS)", 39),
# https://patents.google.com/xhr/query?url=q%3D(TANK)%2BAND%2B((FREQUENCY%2BOR%2BCYCLE)%2BNEAR%252f4%2B(CHANG*%2BOR%2BVARIABLE%2BOR%2BVARY*%2BOR%2BCHANGE%2BOR%2BINCREASE%2BOR%2BDECREASE%2BOR%2BLIGHT%2BOR%2BHEAVY%2BOR%2BFULL%2BOR%2BBIG*%2BOR%2BSMALL*))%252f%2BAND%2B((CHANGE%2BOR%2BVARIABLE%2BOR%2BCHANG*%2B%2BOR%2BINCREASE%2BOR%2BDECREASE%2BOR%2BLIGHT%2BOR%2BHEAVY%2BOR%2BFULL%2BOR%2BBIG*%2BOR%2BSMALL*)%2B5D%2B(LOAD))%2BAND%2B((POWER%2B4D%2B(CONVERT*))%2BOR%2BBOOST%2BOR%2BBUCK%2BOR%2BSMPS)%26oq%3D(TANK)%2BAND%2B((FREQUENCY%2BOR%2BCYCLE)%2BNEAR%252f4%2B(CHANG*%2BOR%2BVARIABLE%2BOR%2BVARY*%2BOR%2BCHANGE%2BOR%2BINCREASE%2BOR%2BDECREASE%2BOR%2BLIGHT%2BOR%2BHEAVY%2BOR%2BFULL%2BOR%2BBIG*%2BOR%2BSMALL*))%252f%2BAND%2B((CHANGE%2BOR%2BVARIABLE%2BOR%2BCHANG*%2B%2BOR%2BINCREASE%2BOR%2BDECREASE%2BOR%2BLIGHT%2BOR%2BHEAVY%2BOR%2BFULL%2BOR%2BBIG*%2BOR%2BSMALL*)%2B5D%2B(LOAD))%2BAND%2B((POWER%2B4D%2B(CONVERT*))%2BOR%2BBOOST%2BOR%2BBUCK%2BOR%2BSMPS)&exp=
("(TANK NEAR/4 RESONA*) AND ((FREQUENCY OR CYCLE) NEAR/4 (CHANG* OR VARIABLE OR VARY* OR \
CHANGE OR INCREASE OR DECREASE OR LIGHT OR HEAVY OR FULL OR BIG* OR SMALL*))/ AND \
((CHANGE OR VARIABLE OR CHANG* OR INCREASE OR DECREASE OR LIGHT OR HEAVY OR FULL OR BIG* OR SMALL*) \
5D (LOAD)) AND ((POWER 4D (CONVERT*)) OR BOOST OR BUCK OR SMPS)", 4),
("((TANK OR LC OR LLC OR LCL) NEAR/4 RESONA*) AND ((FREQUENCY OR CYCLE) NEAR/4 (CHANG* OR VARIABLE \
OR VARY* OR CHANGE OR INCREASE OR DECREASE OR LIGHT OR HEAVY OR FULL OR BIG* OR SMALL*))/ AND \
((CHANGE OR VARIABLE OR CHANG* OR INCREASE OR DECREASE OR LIGHT OR HEAVY OR FULL OR BIG* OR SMALL*) \
5D (LOAD))", 196),
("((TANK OR LC OR LLC OR LCL) NEAR/4 RESONA*) AND ((FREQUENCY OR CYCLE) NEAR/4 (CHANG* OR VARIABLE \
OR VARY* OR CHANGE OR INCREASE OR DECREASE OR LIGHT OR HEAVY OR FULL OR BIG* OR SMALL*))/ AND \
((CHANGE OR VARIABLE OR CHANG* OR INCREASE OR DECREASE OR LIGHT OR HEAVY OR FULL OR BIG* OR SMALL*) \
5D (LOAD OR CURRENT OR SINK))", 459),
("(LOAD NEAR/3 (VALUE OR MAGNITUDE) NEAR/4 (CHANG* OR VARY OR VARIABLE OR INCREASE OR DECREASE OR CHANG*)) \
AND (FREQUENCY NEAR/3 (VALUE OR MAGNITUDE) NEAR/4 (CHANG* OR VARY OR VARIABLE OR INCREASE OR \
DECREASE OR CHANG*))", 135828)
]
if __name__ == "__main__":
# print(test_cases[0])
for i, tc in enumerate(test_cases):
print("Output of test case {} : ".format(i+1))
print(scraper(test_cases[i][0]))
|
{"/main.py": ["/GooglePatentsScraper.py"]}
|
28,771,291
|
worawitkaew/web_for_machine_learning
|
refs/heads/master
|
/hello.py
|
from flask import Flask,render_template
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World"
# ทำตามจาก วิดีโอ
@app.route("/show")
def show():
name = "Diamond"
return render_template("index.html",name=name)
# แสดงhtmlตัวอย่างจากในเว็ป flask
@app.route("/base")
def base():
return render_template("base.html")
@app.route("/registe")
def register():
return render_template("auth/register.html")
@app.route("/logi")
def login():
return render_template("auth/login.html")
if __name__ == "__main__":
app.run(debug=True)
|
{"/app.py": ["/mymodel.py"]}
|
28,784,853
|
cuichaosiig/TrAdaBoost_my
|
refs/heads/main
|
/TrAdaBoost.py
|
import numpy as np
import pandas as pd
import copy
from sklearn.metrics import f1_score, roc_auc_score
class Tradaboost(object):##针对二分类设计的tradaboost
def __init__(self,N=None,base_estimator=None,threshold:float=None,topN:bool = None,score=roc_auc_score):
self.N=N
self.threshold=threshold
self.topN = topN
self.base_estimator=base_estimator
self.best_estimator=np.nan
self.score=score
self.weights = []
self.estimators= []
self.beta_all = np.zeros([1, self.N])
# 权重的标准化,其实差别不大,在前面的例子中也有用到过
def _calculate_weights(self,weights):
total = np.sum(weights)
return np.asarray(weights / total, order='C')
#计算目标域上的错误率
def _calculate_error_rate(self,y_true, y_pred, weight):
total = np.sum(weight)
return np.sum(weight[:, 0] / total * np.abs(y_true - y_pred))
#根据逻辑回归输出的score的得到标签,注意这里不能用predict直接输出标签
def fit(self,source,target,source_label,target_label,early_stopping_rounds):#注意,输入要转为numpy格式的
'''
Source: 待迁移数据
target: 目标数据
return :
更新类中的权重数据
'''
source_shape=source.shape[0]
target_shape=target.shape[0]
trans_data = np.concatenate((source, target), axis=0)
trans_label = np.concatenate((source_label,target_label), axis=0)
weights_source = np.ones([source_shape, 1])/source_shape
weights_target = np.ones([target_shape, 1])/target_shape
weights = np.concatenate((weights_source, weights_target), axis=0)
# 输出统计信息:
N_positive = sum((target_label>0).astype(int))
print(f'''Statistic info:
Size of the source data : {source_shape}
Size of the target data : {target_shape}
Target Npositive:{N_positive}
''')
# 根据公式初始化参数,具体可见原文
bata = 1 / (1 + np.sqrt(2 * np.log(source_shape / self.N)))
result_label = np.ones([source_shape+target_shape, self.N])
trans_data = np.asarray(trans_data, order='C') #行优先
trans_label = np.asarray(trans_label, order='C')
score=0
flag=0
for i in range(self.N):
P = self._calculate_weights(weights) #权重的标准化
self.base_estimator.fit(trans_data,trans_label,P*100)#这里xgb有bug,,如果权重系数太小貌似是被忽略掉了?
self.estimators.append(self.base_estimator)
y_preds=self.base_estimator.predict_proba(trans_data)[:,1] #全量数据的预测
result_label[:, i]=y_preds #保存全量数据的预测结果用于后面的各个模型的评价
#注意,仅仅计算在目标域上的错误率 ,
if self.threshold is not None or self.topN is True:
y_target_pred=self.base_estimator.predict_proba(target)[:,1]#目标域的预测
if self.topN is True:
# 使用topN 进行过滤
rank = pd.DataFrame(y_target_pred,columns=['score'])
rank['rank'] = rank.score.rank(ascending=False)
rank['Y'] = 0
rank.loc[rank['rank']<N_positive,'Y'] = 1
error_rate = self._calculate_error_rate(target_label, rank['Y'].values, \
weights[source_shape:source_shape + target_shape, :])
elif self.threshold is not None:
# 使用阈值进行过滤
error_rate = self._calculate_error_rate(target_label, (y_target_pred>self.threshold).astype(int), \
weights[source_shape:source_shape + target_shape, :])
else:
# 直接使用predict进行处理
y_target_pred=self.base_estimator.predict(target)#目标域的预测
error_rate = self._calculate_error_rate(target_label, y_target_pred, \
weights[source_shape:source_shape + target_shape, :])
#根据不同的判断阈值来对二分类的标签进行判断,对于不均衡的数据集合很有效,比如100:1的数据集,不设置class_wegiht
#的情况下需要将正负样本的阈值提高到99%.
# 防止过拟合
if error_rate > 0.5:
print (f'Error_rate is {error_rate}, scale it !')
error_rate = 0.5
if error_rate == 0:
N = i
break
self.beta_all[0, i] = error_rate / (1 - error_rate)
# 调整目标域样本权重
for j in range(target_shape):
weights[source_shape + j] = weights[source_shape + j] * \
np.power(self.beta_all[0, i],(-np.abs(result_label[source_shape + j, i] - target_label[j])))
# 调整源域样本权重
for j in range(source_shape):
weights[j] = weights[j] * np.power(bata,np.abs(result_label[j, i] - source_label[j]))
# 只在目标域上进行 AUC 的评估
tp=self.score(target_label,y_target_pred)
print('The '+str(i)+' rounds score is '+str(tp),f"Error Rate is {error_rate}")
if tp > score :
score = tp
best_round = i
flag=0
self.best_round=best_round
self.best_score=score
self.weights = weights
self.best_estimator = copy.deepcopy(self.base_estimator)
print('Get a valid weight , updating ...')
else:
flag+=1
if flag >=early_stopping_rounds:
print('early stop!')
break
# 预测代码 -- proba 类别
def predict_prob(self, x_test):
result = np.ones([x_test.shape[0], self.N + 1])
predict = []
i = 0
for estimator in self.estimators:
# 修改,这里采用proba作为预测器,并使用输出为1的作为结果
y_pred = estimator.predict_proba(x_test)[:,1]
result[:, i] = y_pred
i += 1
for i in range(x_test.shape[0]):
left = np.sum(result[i, int(np.ceil(self.N / 2)): self.N] *
np.log(1 / self.beta_all[0, int(np.ceil(self.N / 2)):self.N]) )
right = 0.5 * np.sum( np.log(1 / self.beta_all[0, int(np.ceil(self.N / 2)): self.N]) )
predict.append([left, right])
return predict
|
{"/scorecardpy/indictrans2d.py": ["/scorecardpy/public.py"], "/scorecardpy/indicintersection.py": ["/scorecardpy/public.py"], "/scorecardpy/singlemath.py": ["/scorecardpy/public.py"], "/scorecardpy/discrete.py": ["/scorecardpy/public.py"], "/scorecardpy/__init__.py": ["/scorecardpy/var_filter.py", "/scorecardpy/indictrans2d.py", "/scorecardpy/indicintersection.py", "/scorecardpy/public.py", "/scorecardpy/singlemath.py", "/scorecardpy/discrete.py", "/scorecardpy/timeana.py", "/scorecardpy/describe.py"]}
|
28,828,953
|
a-sinclaire/emitter
|
refs/heads/master
|
/main.py
|
# Sam Laderoute
# Emitter Project
# Apr 22 2021
#
# Create fully customizable emitters
#
# pip install numpy
# pip install pygame
# pip install pygame_widgets
#
import pygame
from pygame.locals import *
from emitter import *
import numpy as np
from pygame_widgets import *
import copy
pygame.init()
width, height = 860, 480
screen = pygame.display.set_mode((width, height))
# SETUP
# emitters = [Emitter(screen, x=1*width / 5, y=height / 2, n_particles=1000, color=(255, 255, 255), lifespan=1000, radius=15, max_r=15, min_r=0, shrink_rate=0.09, density=1, forces=[Force(0.0, np.pi/2, 0.003)]),
# Emitter(screen, x=2*width / 5, y=height / 2, n_particles=50, color=(255, 0, 0), lifespan=3000, radius=5, max_r=40, min_r=0, shrink_rate=-0.05, density=.1, forces=[Force(0.0, np.pi/2, 0.0015)]),
# Emitter(screen, x=3*width / 5, y=height / 2, n_particles=100, color=(0, 255, 0), lifespan=2000, radius=15, max_r=15, min_r=2, shrink_rate=0.02, density=1, forces=[Force(0.3, np.pi/2)]),
# Emitter(screen, x=4*width / 5, y=height / 2, n_particles=100, color=(0, 0, 255), lifespan=1000, radius=8, max_r=30, min_r=0, shrink_rate=0.05, density=.8, forces=[Force(randomV=False, randomAng=True, randomAcc=True)])]
# CUSTOM EMITTERS
# e_candle_flame = Emitter(screen, x=width/2, y=height/2, n_particles=120, color=(255, 140, 0), lifespan=1000, radius=15,
# max_r=50, min_r=0, shrink_rate=0.12, density=1, forces=[Force(velocity=1, ang=np.pi/2)])
# emitters = [e_candle_flame]
f1 = Force(newtons=0.008, ang=np.pi/2)
f2 = Force(random_f=True, random_ang=True)
anti_grav = Force(ang=np.pi/2, acc= 0.001)
e1 = Emitter(screen, x=1*width / 4, y=height / 2, n_particles=500, color=(255, 255, 255), lifespan=250, radius=15,
max_r=25, min_r=0, shrink_rate=0.06, density=0.01, friction=1, forces=[f1])
e2 = Emitter(screen, x=2*width / 4, y=height / 2, n_particles=500, color=(255, 255, 0), lifespan=550, radius=25,
max_r=25, min_r=0, shrink_rate=0.05, density=0.2, friction=1, forces=[f2, anti_grav])
e3 = Emitter(screen, x=3*width / 4, y=height / 2, n_particles=500, color=(255, 0, 0), lifespan=250, radius=3,
max_r=25, min_r=0, shrink_rate=-0.1, density=.1, friction=1, forces=[])
# emitters = [e1, e2, e3]
ScratchEmitter = Emitter(screen, 0.7*width, height/2)
emitters = [ScratchEmitter]
n_particles_slider = Slider(screen, 10, 10, 200, 16, min=0, max=1000, step=1, initial=500)
n_particles_text = TextBox(screen, 220, 10, 100, 20, fontSize=15)
lifespan_slider = Slider(screen, 10, 36, 200, 16, min=0, max=3000, step=20, initial=440)
lifespan_text = TextBox(screen, 220, 36, 100, 20, fontSize=15)
radius_slider = Slider(screen, 10, 62, 200, 16, min=1, max=30, step=1, initial=11)
radius_text = TextBox(screen, 220, 62, 100, 20, fontSize=15)
max_r_slider = Slider(screen, 10, 88, 200, 16, min=0, max=30, step=1, initial=30)
max_r_text = TextBox(screen, 220, 88, 100, 20, fontSize=15)
min_r_slider = Slider(screen, 10, 114, 200, 16, min=0, max=30, step=1, initial=0)
min_r_text = TextBox(screen, 220, 114, 100, 20, fontSize=15)
shrink_rate_slider = Slider(screen, 10, 140, 200, 16, min=0, max=0.1, step=0.005, initial=0.025)
shrink_rate_text = TextBox(screen, 220, 140, 100, 20, fontSize=15)
density_slider = Slider(screen, 10, 166, 200, 16, min=0.001, max=2, step=0.001, initial=0.57)
density_text = TextBox(screen, 220, 166, 100, 20, fontSize=15)
friction_slider = Slider(screen, 10, 192, 200, 16, min=0.01, max=2, step=0.05, initial=0.6)
friction_text = TextBox(screen, 220, 192, 100, 20, fontSize=15)
force_newtons_slider = Slider(screen, 10, 322, 200, 16, min=0, max=3, step=0.01, initial=0)
force_newtons_text = TextBox(screen, 220, 322, 100, 20, fontSize=15)
force_angle_slider = Slider(screen, 10, 348, 200, 16, min=0, max=360, step=1, initial=90)
force_angle_text = TextBox(screen, 220, 348, 100, 20, fontSize=15)
force_acc_slider = Slider(screen, 10, 374, 200, 16, min=0, max=0.003, step=0.0001, initial=0.0022)
force_acc_text = TextBox(screen, 220, 374, 100, 20, fontSize=15)
GRAV_ON = True
WIND_ON = True
def toggle_wind():
global WIND_ON
WIND_ON = not WIND_ON
def toggle_gravity():
global GRAV_ON
GRAV_ON = not GRAV_ON
grav_button = Button(screen, width-110, 10, 100, 20, text="gravity", fontSize=15, onClick=toggle_gravity)
grav_text = TextBox(screen, width-210, 10, 100, 20, fontSize=15)
wind_button = Button(screen, width-110, 36, 100, 20, text="wind", fontSize=15, onClick=toggle_wind)
wind_text = TextBox(screen, width-210, 36, 100, 20, fontSize=15)
sliders = [n_particles_slider, lifespan_slider, radius_slider, max_r_slider, min_r_slider, shrink_rate_slider, density_slider, friction_slider, force_newtons_slider, force_angle_slider, force_acc_slider]
texts = [n_particles_text, lifespan_text, radius_text, max_r_text, min_r_text, shrink_rate_text, density_text, friction_text, force_newtons_text, force_angle_text, force_acc_text, grav_text, wind_text]
buttons = [grav_button, wind_button]
theta = 0
GRAVITY = Force(ang=-np.pi / 2, acc=0.001)
# MAIN LOOP
while True:
events = pygame.event.get()
WIND = Force(newtons=np.cos(theta) * np.random.uniform(0, 0.005), ang=0)
if GRAV_ON:
if WIND_ON:
ENVIRONMENT_FORCES = [GRAVITY, WIND]
else:
ENVIRONMENT_FORCES = [GRAVITY]
else:
if WIND_ON:
ENVIRONMENT_FORCES = [WIND]
else:
ENVIRONMENT_FORCES = []
theta += 0.01
theta %= np.pi * 2
# BACKGROUND
screen.fill((30, 30, 30))
# LISTEN FOR SLIDER EVENTS / SET TEXT
for s in sliders:
s.listen(events)
for b in buttons:
b.listen(events)
n_particles_text.setText("n_particles: " + str(n_particles_slider.getValue()))
lifespan_text.setText("lifespan: " + str(lifespan_slider.getValue()))
radius_text.setText("radius: " + str(radius_slider.getValue()))
min_r_text.setText("min_r: " + str(min_r_slider.getValue()))
max_r_text.setText("max_r: " + str(max_r_slider.getValue()))
shrink_rate_text.setText("shrink_rate: " + str(shrink_rate_slider.getValue()))
density_text.setText("density: " + str(density_slider.getValue()))
friction_text.setText("friction: " + str(friction_slider.getValue()))
force_newtons_text.setText("force_newtons: " + str(force_newtons_slider.getValue()))
force_angle_text.setText("force_angle: " + str(force_angle_slider.getValue()))
force_acc_text.setText("force_acc: " + str(force_acc_slider.getValue()))
grav_text.setText("gravity: " + str(GRAV_ON))
wind_text.setText("wind: " + str(WIND_ON))
# DRAW SLIDERS AND TEXT
for s in sliders:
s.draw()
for t in texts:
t.draw()
for b in buttons:
b.draw()
# UPDATE FROM SLIDER EVENTS
ScratchEmitter.n_particles = n_particles_slider.getValue()
ScratchEmitter.lifespan = lifespan_slider.getValue()
ScratchEmitter.radius = radius_slider.getValue()
ScratchEmitter.min_r = min_r_slider.getValue()
ScratchEmitter.max_r = max_r_slider.getValue()
ScratchEmitter.shrink_rate = shrink_rate_slider.getValue()
ScratchEmitter.density = density_slider.getValue()
ScratchEmitter.friction = friction_slider.getValue()
ScratchEmitter.forces = [Force(newtons=force_newtons_slider.getValue(), ang=np.deg2rad(force_angle_slider.getValue()), acc=force_acc_slider.getValue())]
# for testing
ScratchEmitter.apply_forces(ENVIRONMENT_FORCES)
emitters[0] = ScratchEmitter
# DRAW ELEMENTS
for e in emitters:
if pygame.key.get_pressed()[pygame.K_SPACE]:
e.apply_forces([Force(newtons=1, random_ang=True)])
e.apply_forces(ENVIRONMENT_FORCES)
e.update()
e.draw()
# UPDATE THE SCREEN
pygame.display.flip()
# CHECK EVENTS
for event in events:
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
|
{"/main.py": ["/emitter.py"]}
|
28,828,954
|
a-sinclaire/emitter
|
refs/heads/master
|
/emitter.py
|
import pygame
import numpy as np
import copy
class Force:
def __init__(self, newtons=0, ang=0, acc=0, random_f=False, random_ang=False):
self.newtons = newtons
self.ang = ang % (2 * np.pi)
self.acc = acc
self.random_f = random_f
self.random_ang = random_ang
class Particle:
def __init__(self, screen, x, y, color, lifespan, radius, max_r, min_r, shrink_rate, density, friction, forces):
self.screen = screen
self.x = x
self.y = y
self.color = color
self.lifespan = lifespan
self.age = 0
self.vx = 0
self.vy = 0
self.radius = radius
self.start_r = radius
self.max_r = max_r
self.min_r = min_r
self.shrink_rate = shrink_rate
self.density = density
self.friction = friction
self.forces = forces
self.mass = self.density * self.start_r**2*np.pi
def apply_forces(self, forces):
for f in forces:
if f.random_ang:
f.ang = np.random.uniform(-np.pi, np.pi)
if f.random_f:
f.newtons = np.random.uniform(0.0, 1.0)
acc = f.newtons / self.mass
acc += f.acc
acc *= 1/self.friction
self.vx += np.cos(f.ang) * acc
self.vy -= np.sin(f.ang) * acc
self.x += self.vx
self.y += self.vy
def is_dead(self):
return self.age > self.lifespan or self.radius < 1 or self.x < 0 or self.x > pygame.display.get_surface().get_width() or self.y < 0 or self.y > pygame.display.get_surface().get_height()
def update(self):
self.age += 1
self.radius -= self.shrink_rate
if self.radius > self.max_r: self.radius = self.max_r
if self.radius < self.min_r: self.radius = self.min_r
area = self.radius ** 2 * np.pi
self.mass = self.density*area
self.apply_forces(self.forces)
def draw(self):
pygame.draw.circle(self.screen, self.color, (self.x, self.y), self.radius)
class Emitter:
def __init__(self, screen, x, y, n_particles=100, color=(255,255,255), lifespan=100, radius=10, max_r=np.inf, min_r=0, shrink_rate=0.01, density=1, friction=1, forces=[]):
self.screen = screen
self.x = x
self.y = y
self.n_particles = n_particles
self.color = color
self.lifespan = lifespan
self.radius = radius
self.max_r = max_r
self.min_r = min_r
self.shrink_rate = shrink_rate
self.density = density
self.friction = friction
self.forces = forces
self.particles = []
def update(self):
temp_list = []
for p in self.particles:
# REMOVE DEAD PARTICLES
if not p.is_dead():
temp_list.append(p)
self.particles = temp_list
for p in self.particles:
# UPDATE EACH PARTICLE
p.update()
# ADD PARTICLES IF NEEDED
if len(self.particles) < self.n_particles:
self.particles.append(
Particle(self.screen, self.x, self.y, self.color, self.lifespan, self.radius, self.max_r, self.min_r, self.shrink_rate, self.density,
self.friction, copy.deepcopy(self.forces)))
def apply_forces(self, forces):
for p in self.particles:
p.apply_forces(forces)
def draw(self):
for p in self.particles:
p.draw()
|
{"/main.py": ["/emitter.py"]}
|
28,889,840
|
dwyer/folklorist
|
refs/heads/main
|
/folklorist/folklorist/settings_prod.py
|
from folklorist.settings import *
DEBUG = False
ALLOWED_HOSTS.append('folklorist.org')
|
{"/folklorist/tbi/views.py": ["/folklorist/tbi/mixins.py", "/folklorist/tbi/models.py", "/folklorist/tbi/utils.py"], "/folklorist/tbi/models.py": ["/folklorist/tbi/utils.py"]}
|
28,894,698
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/models/dbnet_armnn.py
|
import time
from pathlib import Path
import pyarmnn as ann
from .dbnet_base import DBNet
class DBNetArmNN(DBNet):
def __init__(self, model_path, preprocess, runtime, backend, logger, **kwargs):
super().__init__(logger, **kwargs)
self.graph_id = 0
parser = ann.ITfLiteParser()
netIdx = 0
if Path(model_path).exists():
net = parser.CreateNetworkFromBinaryFile(model_path)
elif model_path == "landscape":
net = parser.CreateDetLandscape()
netIdx = 4
elif model_path == "portrait":
net = parser.CreateDetPortrait()
netIdx = 5
else:
raise ValueError(f"Invalid model path: {model_path}")
self.preproc_mode = preprocess
self.runtime = runtime.runtime
self.infer_idx = runtime.get_infer_idx()
opt_options = ann.OptimizerOptions(backend=="GpuAcc", False, False, False, netIdx)
from inspect import getmembers
logger.info(f"Det Backend: {backend}, FP16 Turbo Mode: {opt_options.m_ReduceFp32ToFp16}")
preferredBackends = [ann.BackendId(backend)]
opt_net, msg = ann.Optimize(net, preferredBackends, self.runtime.GetDeviceSpec(), opt_options)
self.net_id, _ = self.runtime.LoadNetwork(opt_net)
nodes_in = parser.GetSubgraphInputTensorNames(self.graph_id)
assert len(nodes_in) == 1, f'{len(nodes_in)} inputs found, 1 expected'
self.input_info = parser.GetNetworkInputBindingInfo(self.graph_id, nodes_in[0])
self.input_shape = tuple(self.input_info[1].GetShape())
self.input_h = self.input_shape[1]
self.input_w = self.input_shape[2]
logger.info(f"DetNet input shape: {self.input_shape}")
nodes_out = parser.GetSubgraphOutputTensorNames(self.graph_id)
assert len(nodes_out) == 1, f'{len(nodes_out)} outputs found, 1 expected'
self.output_info = parser.GetNetworkOutputBindingInfo(self.graph_id, nodes_out[0])
self.output_tensors = ann.make_output_tensors([self.output_info])
self.logger = logger
def infer_sync(self, img):
feed = self.preprocess(img)
t0 = time.time()
input_tensors = ann.make_input_tensors([self.input_info], [feed])
self.runtime.EnqueueWorkload(self.net_id, input_tensors, self.output_tensors)
result = ann.workload_tensors_to_ndarray(self.output_tensors)[0]
self.logger.debug(f'DBnet enqueue: {time.time() - t0:.3f}s')
boxes, scores, angle = self.parse_result(result)
return boxes, scores, angle
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,699
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/utils/text.py
|
"""
Subset of the same module in mainstream ocr2
"""
import regex as re
NUM_FIX = {
'l': '1',
'i': '1',
'Ⅰ': '1',
't': '1',
'」': '1',
'「': '1',
'丁': '1',
'亅': '1',
'}': '1',
'{': '1',
'o': '0',
's': '5',
'g': '9',
}
dup_nums = re.compile(r'\D{2,}\d{3}[年月日]')
def fix_num(text):
text = text.replace('5印年', '50年')
use_fix = False
if re.findall('[年月日]\D[年月日]', text):
use_fix = True
if '番号' in text or '記号' in text:
use_fix = True
if len(text) == 2 and text[1] == '割':
use_fix = True
if use_fix:
for k in NUM_FIX:
text = text.replace(k, NUM_FIX[k])
return text
def clean_year(line):
matched = dup_nums.search(line[-1])
if matched is None:
return line
start, end = matched.span()
if line[0][1][start:end-1].min() > 0.95:
return line
rm_idx = line[0][1][start:end-1].argmin() + start
line[-1] = line[-1][:rm_idx] + line[-1][rm_idx+1:]
return line
def get_date(txt, return_jp_year):
def search(pattern, txt):
suffix = '([^\d-])\s*(0[1-9]|[1-9]|1[0-2])([^\d-])\s*(0[1-9]|[1-9]|[1-2][0-9]0*|3[0-1]0*|99)(\D|$)'
m = re.findall(pattern + suffix, txt)
return m
def western_year(m, offset, return_jp_year):
if return_jp_year:
dates = [(str(int(gs[1]) + offset) + gs[3].zfill(2) + gs[5][:2].zfill(2), gs[1].zfill(2) + gs[3].zfill(2) +
gs[5][:2].zfill(2)) for gs in m]
else:
dates = [str(int(gs[1]) + offset) + gs[3].zfill(2) + gs[5][:2].zfill(2) for gs in m]
return dates
txt = re.sub('\D年', '元年', txt)
txt = txt.replace('元年', '1年').replace(' ', '')
txt = txt.replace('末日', '99日').replace('未目', '99日').replace('末目', '99日').replace('未日', '99日')
m_r = search('(令和|合和)(0[1-9]|[1-9]|[1-9][0-9])', txt)
m_h = search('(平成(?<!\d)){e<2}(0[1-9]|[1-9]|[1-4][0-9])', txt)
m_s = search('(昭[^\d\s\pP])(0[1-9]|[1-9]|[1-5][0-9]|6[0-4])', txt)
m_d = search('(大正(?<!\d)){e<2}(0[1-9]|[1-9]|1[0-5])', txt)
m_m = search('(明治(?<!\d)){e<2}(0[1-9]|[1-9]|[1-3][0-9]|4[0-5])', txt)
m_w = search('(19[0-9]{2}|2[0-9]{3})', txt)
dates = []
if m_m:
dates += western_year(m_m, 1867, return_jp_year)
if m_d:
dates += western_year(m_d, 1911, return_jp_year)
if m_s:
dates += western_year(m_s, 1925, return_jp_year)
if m_h:
dates += western_year(m_h, 1988, return_jp_year)
if m_r:
dates += western_year(m_r, 2018, return_jp_year)
if m_w:
dates += [(gs[0]+gs[2].zfill(2)+gs[4].zfill(2),) for gs in m_w]
return dates
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,700
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/finders/jgngak.py
|
"""A finder to extract 限度額 from OCR results"""
from typing import List, Any, Union
import yaml
from ..re_pattern import DEDUCTIBLE_TAG, DEDUCTIBLE_AMT, DEDUCTIBLE_WITH_TAG, DEDUCTIBLE_TAGS
class JgnGakFinder(yaml.YAMLObject):
"""A finder class to extract 限度額 from text lines output by OCR.
Typical usage example:
>>> finder = JgnGakFinder()
>>> res = finder.extract([
["限度額"],
["通院1,000円/月"],
["入院1,000円/月"],
])
>>> print(res)
通院 1,000;入院 1,000;
"""
yaml_tag = u'!JgnGakFinder'
def _get_amount(self, line):
limit = DEDUCTIBLE_AMT.findall(line[-1])
if limit:
self.info['JgnGak'] = limit[0].replace('o', '0')
if self.info['JgnGak'][0] == '0' and len(self.info["JgnGak"]) > 1:
self.info['JgnGak'] = '1' + self.info['JgnGak']
return self.info['JgnGak']
return None
def _get_multi(self, texts: List[List[Any]]) -> str:
"""Extracts multile deductible values if possible.
e.g. 入院 and 入院外 each has a deductible
Args:
texts: OCR results in a list, each element of each has also to be a
list, each element of which is the text for each detected line.
Returns:
A string containing multiple 限度額 if any, empty string otherwise.
"""
flags = [True for _ in range(len(DEDUCTIBLE_TAGS))]
res = ""
for line in texts:
for idx, (tag, pattern, need) in enumerate(zip(
DEDUCTIBLE_TAGS,
DEDUCTIBLE_WITH_TAG,
flags
)):
if not need: continue
matched = pattern.findall(line[-1])
if matched and matched[0] is not None:
res += tag + " " + matched[0].replace('o', '0') + ";"
flags[idx] = False
return res
def extract(self, texts: List[List[Any]]) -> Union[str, None]:
"""Extracts 限度額 from text lines if possible.
Args:
texts: OCR results in a list, each element of each has also to be a
list, each element of which is the text for each detected line.
Returns:
A string of 限度額 if anything extracted, `None` otherwise.
"""
self.info = {}
multi_res = self._get_multi(texts)
if multi_res: return multi_res
for line in texts:
if DEDUCTIBLE_TAG.search(line[-1]):
amount = self._get_amount(line)
if amount: return amount
print('JgnGak with tag not found, search yen in each line')
for line in texts:
amount = self._get_amount(line)
if amount: return amount
if "JgnGak" not in self.info:
self.info["JgnGak"] = None
return None
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,701
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/kouhi_analyzer.py
|
"""Analyzer that extracts key information from OCR resutls of 公費保険"""
from typing import List, Any
from .finders import JgnGakFinder, RouFtnKbnFinder
from .match import kohi_num_match, insurer_match
from .extract import get_date
from .re_pattern import KIGO
from .analyzer_base import AnalyzerBase
date_tags = [
"入院",
"入院外",
"外来",
"通院",
"調剤",
"無",
"1割"
]
class KouhiAnalyzer(AnalyzerBase):
"""Analyzer to extract key information from OCR results of 公費保険証.
It tries to extract as much keyinformation as possible when `fit` is called.
The input argument `texts` of `fit` is a list containing OCR results, each
element of which also has to be a list, whose last element has to be text of
one line.
All extracted information is stored in info, and can be queried by tag via
`get`.
Typical usage example:
>>> analyzer = MainAnalyzer()
"""
def __init__(self):
config = {
"HknjaNum": "wide_finder",
"Num": "simple_finder",
("Birthday", "YukoStYmd", "YukoEdYmd", "KofuYmd"): "dates_finder",
"JgnGak": JgnGakFinder(),
"RouFtnKbn": RouFtnKbnFinder(),
}
super().__init__(config)
def fit(self, texts):
self._finder_fit(texts)
self._handle_nums(texts)
self._handle_kigo(texts)
self._handle_multi_dates(texts)
def _handle_nums(self, texts: List[List[Any]]):
"""Handles hknjanum and num on the same line.
Args:
texts: OCR results in a list.
"""
if self._have("HknjaNum") and self._have("Num"): return
for idx, line in enumerate(texts[:5]):
ret1, _ = insurer_match(line[-1])
ret2, _ = kohi_num_match(line[-1])
if ret1 and ret2 and idx + 1 < len(texts):
next_line = texts[idx + 1][-1]
if next_line.isdigit():
self.info["HknajaNum"] = next_line[:8]
self.info["Num"] = next_line[8:]
def _handle_kigo(self, texts):
# special handling for kigo
if self._have("Kigo"): return
self.info["Kigo"] = None
for line in texts:
for pattern in KIGO:
match = pattern.findall(line[-1])
if match and match[0] is not None:
self.info["Kigo"] = match[0]
def _handle_multi_dates(self, texts: List[List[Any]]):
"""Handles multiple dates.
Args:
texts: OCR results in a list.
"""
froms = []
untils = []
for idx, line in enumerate(texts):
has_from = "から" in line[-1] or (len(line[-1]) > 2 and line[-1][-2]) == "か"
has_until = "迄" in line[-1] or "まで" in line[-1]
if not has_from and not has_until: continue
dates = get_date(line[-1])
if has_from and has_until and len(dates) == 2:
froms.append((idx, dates[0]))
untils.append((idx, dates[1]))
continue
if has_from and len(dates) == 1:
froms.append((idx, dates[0]))
if has_until and len(dates) == 1:
untils.append((idx, dates[0]))
if not (len(untils) > 1 and len(froms) > 1): return
new_st = ""
new_ed = ""
for (idx_f, date_f), (idx_u, date_u) in zip(froms, untils):
start = max(0, idx_f - 2, idx_u - 2)
end = min(len(texts) - 1, idx_f + 2, idx_u + 2)
for cidx in range(start, end + 1):
for tag in date_tags:
if tag in texts[cidx][-1].replace("憮", "無"):
new_st += tag + " " + str(date_f) + ";"
new_ed += tag + " " + str(date_u) + ";"
texts[cidx][-1].replace(tag, "")
if new_st and new_ed:
self.info["YukoStYmd"] = new_st
self.info["YukoEdYmd"] = new_ed
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,702
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/__init__.py
|
"""A collection of applications that use a model server for OCR on images and
extract key infomation from the results."""
from .apps import InsuranceReader
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,703
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/models/__init__.py
|
try:
from .ctpnp_openvino import CTPNP_OpenVINO
from .dense8_openvino import Dense8_OpenVINO
except ModuleNotFoundError:
print('OpenVINO not installed')
try:
from .dbnet_armnn import DBNetArmNN
from .dense8_armnn import Dense8ArmNN
except ModuleNotFoundError:
print('PyArmNN is not installed')
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,704
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/camera/client.py
|
import time
import numpy as np
import zmq
from utils import ensure_type
class CamClient:
def __init__(self, conf):
port = conf["zmq"]["port"]
ensure_type(port, int)
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.setsockopt(zmq.SUBSCRIBE, b"")
socket.setsockopt(zmq.CONFLATE, 1)
socket.connect(f"tcp://localhost:{port}")
self.socket = socket
def read(self):
raw = self.socket.recv()
img = np.frombuffer(raw, dtype=np.uint8).reshape(1944, 2592, 3)
return img
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,705
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/date.py
|
"""A date class that can output string in different formats"""
ERA_OFFSET = {
"m": 1867,
"t": 1911,
"s": 1925,
"h": 1988,
"r": 2018,
"w": 0,
}
MONTH_LAST_DAY = {
'01':'31',
'02':'28',
'03':'31',
'04':'30',
'05':'31',
'06':'30',
'07':'31',
'08':'31',
'09':'30',
'10':'31',
'11':'30',
'12':'31',
}
class Date:
"""Date class to hold year, month, day, and can output date string.
Supported formats of output string:
1. western style in digits
2. short form used in mynumber card PIN generation
Typical usage example:
>>> d1 = Date(year="2021", month="1", date="22", era="w")
>>> print(d1)
20210122
>>> print(d1.western_str())
20210122
>>> print(d1.mynum_str())
210122
>>> d2 = Date(year="3", month="2", date="22", era="h")
>>> print(d2)
19910222
>>> print(d2.western_str())
19910222
>>> print(d2.mynum_str())
030222
Args:
year: Year digits in string
month: Month digits in string
date: Day digits in string
era: Japanese era tag in string.
(m: 明治, t: 大正, s: 昭和, h: 平成, r: 令和, w: 西暦)
"""
def __init__(self, year: str, month: str, date: str, era: str):
self.m = month
self.d = date
self.y = str(int(year) + ERA_OFFSET[era])
self.jpy = year if era != "w" else None
self.check_last_day()
def western_str(self):
"""Generates date string using western year."""
date_str = self.y + self.m.zfill(2) + self.d.zfill(2)
return date_str
def mynum_str(self):
"""Generates string for MyNumber card verification."""
if self.jpy is None:
date_str = self.y[-2:] + self.m.zfill(2) + self.d.zfill(2)
else:
date_str = self.jpy.zfill(2) + self.m.zfill(2) + self.d.zfill(2)
return date_str
def __repr__(self):
return self.western_str()
def __str__(self):
return self.western_str()
def check_last_day(self):
if str(self.d) == '99':
if str(self.m.zfill(2)) == '02' and int(self.y)%4 ==0:
self.d=29
else:
self.d = MONTH_LAST_DAY[str(self.m.zfill(2))]
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,706
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/mynum_reader.py
|
import time
import logging
import pickle
import unicodedata
from pathlib import Path
import multiprocessing
import subprocess
import cv2
import numpy as np
import regex as re
from .base_reader import BaseReader
from .utils.general import get_date_roi, get_num_roi
from .utils.text import get_date, fix_num, clean_year
from .utils.image import max_iou, dilate_erode, sharpen, read_scope, box_crop
from info_extractor.date import Date
import time
INFO_ITEMS = {
'マイナンバーカード': {
'Birthday': '生年月日',
'YukoEdYmd': '有効終了日',
'Code': '4桁コード',
}
}
def match(img, target, method=cv2.TM_CCOEFF_NORMED, blur=5):
img_blur = cv2.GaussianBlur(img, (blur, blur), 0)
res = cv2.matchTemplate(img_blur, target, method)
_, max_v, _, max_loc = cv2.minMaxLoc(res)
return max_v, max_loc
class MyNumReader(BaseReader):
def __init__(self, client, logger, conf):
super().__init__(client=client, logger=logger, conf=conf)
self.mark = cv2.imread('mynum_mark_processed.jpg', cv2.IMREAD_GRAYSCALE)
self.mark_flip = cv2.rotate(self.mark, cv2.ROTATE_180)
self.tm_threshold = 0.7
#self.tm_threshold = -1
self.syukbn = 'Unknown'
self.scanned = False
self.prob = {}
self.n_retry = 2
self.load_scope()
self.skip_rot = True
def load_scope(self):
self.scope = read_scope("scope.txt")
@staticmethod
def clean_half_width(texts):
"""
Borrowed from mainstream insurance reader
"""
for idx, line in enumerate(texts):
for idx_w, w in enumerate(line[:-1]):
text, probs, positions, box = w
# clean nums
x_dist = positions[1:] - positions[:-1]
close_indices = np.where(x_dist < 32)
if close_indices[0].size > 0 and all([not c.isdigit() for c in text]):
for idx_m in close_indices[0]:
if unicodedata.normalize('NFKC', text[idx_m]) == unicodedata.normalize('NFKC', text[idx_m + 1]):
texts[idx][idx_w][0] = text[:idx_m] + text[idx_m] + text[idx_m+2:]
texts[idx][idx_w][1][idx_m:idx_m+2] = [probs[idx_m]]
texts[idx][idx_w][2][idx_m:idx_m+2] = [positions[idx_m]]
texts[idx][-1] = ''.join([l[0] for l in texts[idx][:-1]])
texts[idx][-1] = unicodedata.normalize('NFKC', fix_num(line[-1])).upper()
return texts
def rotate_and_validate(self, img):
if img.shape[0] > img.shape[1]:
img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
self.logger.info('Portrait layout detected for my number card, rotating...')
h, w = img.shape[:2]
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
ori_max, max_loc = match(img_gray[:h//2, w//2:], self.mark)
flip_max, max_loc_flip = match(img_gray[h//2:, :w//2], self.mark_flip)
self.logger.info(f'TM max value: {ori_max :.3f}')
self.logger.info(f'TM max value after flipping: {flip_max :.3f}')
self.logger.info(f'TM threshold: {self.tm_threshold}')
if ori_max < self.tm_threshold and flip_max < self.tm_threshold:
#return img, False
self.logger.info('No matched mynum mark, assuming mark on outter side')
self.max_loc = (1200, 50)
return img, True
if ori_max > flip_max:
self.max_loc = (max_loc[0] + w // 2, max_loc[1])
return img, True
self.logger.info("Image seems upsidedown, flipping...")
x = w - (max_loc_flip[0] + self.mark_flip.shape[1])
y = h - (max_loc_flip[1] + h // 2 + self.mark_flip.shape[0])
self.max_loc = (x, y)
img_flip = cv2.rotate(img, cv2.ROTATE_180)
return img_flip, True
def get_chip(self, img, boxes, roi, lower_y=False, num_sp=False):
max_v, max_idx = max_iou(boxes, roi)
force_roi = False
if max_v > 0:
box = boxes[max_idx]
if num_sp:
box[3] += int((box[3] - box[1]) * 0.15)
self.logger.info("Using temp fix for num chip")
else:
box = roi
box[0] += 5
box[2] -= 20
box[1] += 20
box[3] = box[3] - 15 if lower_y else box[3] - 20
force_roi = True
#TODO: use better handling
if box[1] >= box[3]:
box[1], box[3] = 0, 32
if box[0] >= box[2]:
box[2], box[2] = 0, 32
box = box.astype(int)
chip = img[box[1]:box[3], box[0]:box[2]]
return chip, box, max_idx, force_roi
def save_chip(self, chip, name):
if not name.endswith(".jpg"):
name += ".jpg"
save_path = str(self.debug_out / name)
cv2.imwrite(save_path, chip[..., ::-1])
def draw_roi(self, img, roi, name):
img_draw = img.copy()
cv2.rectangle(img_draw, (roi[0], roi[1]), (roi[2], roi[3]), (255, 0, 0), 2)
if not name.endswith(".jpg"): name += ".jpg"
save_path = str(self.debug_out / name)
cv2.imwrite(save_path, img_draw[..., ::-1])
def get_date_chip(self, img, boxes):
date_roi = get_date_roi(self.max_loc[0], self.max_loc[1], img.shape[1], img.shape[0])
chip, box, box_idx, force_roi = self.get_chip(img, boxes, date_roi, lower_y=True)
if 32 / chip.shape[0] * chip.shape[1] < 400:
for b_idx, b in enumerate(boxes):
if b_idx == box_idx:
continue
inter_y1 = max(b[1], box[1])
inter_y2 = min(b[3], box[3])
union_y1 = min(b[1], box[1])
union_y2 = max(b[3], box[3])
#if max(inter_y2 - inter_y1, 0) / (union_y2 - union_y1) > 0.6:
if max(inter_y2 - inter_y1, 0) / (union_y2 - union_y1) > 0.3:
x1 = int(min(b[0], box[0]))
x2 = int(max(b[2], box[2]))
y1 = int(min(b[1], box[1]))
y2 = int(max(b[3], box[3]))
box = np.array([x1, y1, x2, y2])
chip = img[y1:y2, x1:x2]
if self.debug["draw_date_roi"]:
self.draw_roi(img, date_roi, "date_roi")
if self.debug["save_chips"]:
self.save_chip(chip, "date")
self.date_chip = chip
chip = dilate_erode(chip)
return chip, box
def get_num_chip(self, img, boxes):
num_roi = get_num_roi(self.max_loc[0], self.max_loc[1], img.shape[1], img.shape[0])
if self.debug["draw_num_roi"]:
self.draw_roi(img, num_roi, "num_roi")
chip, box, box_idx, force_roi = self.get_chip(img, boxes, num_roi, num_sp=True)
if self.debug["save_chips"]:
self.save_chip(chip, "num")
self.num_chip = chip
return chip, box
def get_bdate_yukoymd(self):
for l in self.texts:
if 'Birthday' in self.info: break
dates = get_date(l[-1], return_jp_year=True)
if len(dates) != 2 and l[0][1].size > 0:
if l[0][1].min() < 0.95:
rm_idx = l[0][1].argmin()
dates = get_date(l[-1][:rm_idx] + l[-1][rm_idx+1:], return_jp_year=True)
if len(dates) == 2:
if isinstance(dates[0], tuple):
self.info['Birthday'] = dates[0][-1]
else:
self.info['Birthday'] = dates[0]
if isinstance(dates[1], tuple):
self.info['YukoEdYmd'] = dates[1][0]
else:
self.info['YukoEdYmd'] = dates[1]
prob = min(l[0][1])
self.prob['Birthday'] = prob
self.prob['YukoEdYmd'] = prob
if len(self.info.get('Birthday', '')) == 8:
self.info['Birthday'] = self.info['Birthday'][2:]
def get_code(self):
with open('texts-code.txt','w') as f:
f.write(str(self.texts))
for l in self.texts:
if 'Code' in self.info: break
if l[-1].isdigit() and len(l[-1]) == 4:
self.info['Code'] = l[-1]
self.prob['Code'] = min(l[0][1])
if 'Code' not in self.info:
self.logger.warning('No 4-digit PIN found, grabbing last digits from each line')
self.logger.warning('3-digit kara 4-difit ni tasu!')
for l in self.texts:
codes = re.findall(r'\d{3,4}$', l[-1])
if codes:
if len(codes[-1])==4:
pass
else:
self.logger.warning('code3 debug: '+ str(codes[-1]))
code3 = codes[-1]
if code3[0] == code3[1]:
code3 = code3[1] + code3
elif code3[2] == code3[1]:
code3 = code3 + code3[1]
codes[-1] = code3
##
self.info['Code'] = codes[-1]
self.prob['Code'] = min(l[0][1])
break
def crop(self, img, margin):
img = img.copy()
x1, y1, x2, y2 = self.scope if margin is None else margin
img = img[y1:y2, x1:x2]
return img
def draw_max_loc(self, img):
img = img.copy()
cv2.rectangle(img,
(self.max_loc[0], self.max_loc[1]),
(self.max_loc[0] + 100, self.max_loc[1] + 100), (255, 0, 0), 2)
save_path = str(self.debug_out / "max_loc.jpg")
cv2.imwrite(save_path, img)
def get_chip_box(self, img, margin=None):
img = self.crop(img, margin)
img, valid = self.rotate_and_validate(img)
boxes, scores = self.find_texts(img)
chip_img = self.det_img if self.recog_preproc == self.det_preproc else self.img
_, date_box = self.get_date_chip(chip_img, boxes)
_, num_box = self.get_num_chip(chip_img, boxes)
return date_box, num_box
def ocr(self, img, category, margin=None):
self.info = {}
img = self.crop(img, margin)
img, valid = self.rotate_and_validate(img)
if self.debug["draw_max_loc"]: self.draw_max_loc(img)
if valid:
counter = 0
while counter < self.n_retry:
counter += 1
self.syukbn = "マイナンバーカード"
try:
t0 = time.time()
boxes, scores = self.find_texts(img)
print(f"find texts: {time.time() - t0:.3f}")
except Exception as e:
boxes = np.array([])
scores = np.array([])
self.logger.info(f'{len(boxes)} text boxes detected')
if len(boxes) == 0: continue
texts = []
chip_img = self.det_img if self.recog_preproc == self.det_preproc else self.img
# date
chip, box = self.get_date_chip(chip_img, boxes)
self.date_chip = chip
date_line = self.read_single_line(chip, box, num_only=False)
##debug date line
with open('date-line-mae.txt','w') as f:
f.write(str(date_line[-1])+'\n')
f.write(str(boxes)+'\n')
f.write(str(box)+'\n')
if re.findall('(昭.|平成|令和|合和|大正|明治).*',date_line[-1]):
pass
else:
box[0] = box[0]-120
chip, box = self.get_date_chip(chip_img, [box])
date_line = self.read_single_line(chip, box, num_only=False)
with open('date-line-shusei.txt','w') as f:
f.write(str(date_line[-1])+'\n')
f.write(str(boxes)+'\n')
f.write(str(box)+'\n')
##debug
if len(date_line[-1]) > 0:
texts.append(date_line)
self.logger.debug(f'Recogized date text: {date_line[-1]}')
self.logger.debug(f'Probs: {str(date_line[0][1])}')
else:
self.logger.warning('No text recognized for date')
continue
# num
chip, box = self.get_num_chip(chip_img, boxes)
num_box = box
num_line = self.read_single_line(chip, box, num_only=True)
if len(num_line[-1]) < 4:
self.logger.warning('Fewer than 4 chars recognied in num roi, sharpen and try again')
chip = sharpen(chip)
num_line = self.read_single_line(chip, box, num_only=True)
if num_line[0][1].size > 0:
if num_line[0][1].min() < 0.95:
self.logger.warning('Low confidence for num, sharpen and try again')
chip_sharp = sharpen(chip)
num_line_new = self.read_single_line(chip_sharp, box, num_only=True)
if num_line_new[0][1].size > 0:
if num_line_new[0][1].min() > num_line[0][1].min():
self.logger.warning('sharpen result used')
num_line = num_line_new
else:
self.logger.warning('sharpen result has lower confidence, discarded')
if len(num_line[-1]) < 4:
self.logger.warning('Fewer than 4 chars recognied in num roi, re_crop and try again')
print(chip.shape)
l,r = self.re_crop_num_chip(chip)
# temp_chip = chip_img[num_box[1]:num_box[3], num_box[0]:num_box[2]]
bias = 10
l = max(l -bias,0)
r = min(r +bias,chip.shape[1])
new_num_chip = chip[:,l:r]
cv2.imwrite('num_chip.jpg',new_num_chip)
print(new_num_chip.shape)
num_line = self.read_single_line(new_num_chip, num_box, num_only=True)
if len(num_line[-1]) > 0:
texts.append(num_line)
self.logger.debug(f'Recognized num text: {num_line[-1]}')
self.logger.debug(f'Probs: {str(num_line[0][1])}')
else:
self.logger.warning('No text recognized for num')
continue
texts = [clean_year(line) for line in self.clean_half_width(texts)]
self.texts = texts
self.get_bdate_yukoymd()
self.get_code()
done = True
for k in ["Birthday", "YukoEdYmd", "Code"]:
if k not in self.info:
self.logger.warning(f"Cannot find {k}")
done = False
break
if done: break
else:
self.syukbn = 'Unknown'
now = time.localtime()
name = ''
for i in now[0:6]:
name = name + str(i) + '-'
try:
with open('./debug/texts-all'+name+'.txt','w') as f:
f.write(str(texts))
except:
with open('./debug/texts-all'+name+'.txt','w') as f:
f.write('1\n')
return self.syukbn
def re_crop_num_chip(self,img):
gray_img = cv2.cvtColor(img.copy(),cv2.COLOR_RGB2GRAY)
code_line = gray_img[gray_img.shape[0]//2,:]
avg = np.sum(gray_img)//gray_img.reshape([-1]).shape[0]
#left
value = code_line[code_line<avg][0]
l_idx = list(code_line).index(value)
#right
value = code_line[code_line<avg][-1]
r_idx = len(code_line)-list(code_line[::-1]).index(value)
print(l_idx,r_idx)
return l_idx,r_idx
def extract_info(self, key: str):
"""
Borrowed from mainstream insurance reader
"""
if key == 'SyuKbn':
return self.syukbn
else:
text = self.info.get(key, None)
if not isinstance(text, list) and text!=None and not isinstance(text, str):
text = str(text)
result = {"text": text, "confidence": 1.0}
return result
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,707
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/extract.py
|
import numpy as np
from .re_pattern import DATE, LAST_DAY, INSURER, ANY_NUM, INSURER_NUM
from .date import Date
def clean_date(text: str):
text = text.replace("元年", "1年")
text = LAST_DAY.sub("99日", text)
return text
def get_date(text: str):
text = clean_date(text)
dates = []
for era, pattern in DATE.items():
matches = pattern.findall(text)
if matches:
for m in matches:
if m[0].isdigit():
dates.append(Date(year=m[0], month=m[2], date=m[4], era=era))
else:
dates.append(Date(year=m[1], month=m[3], date=m[5], era=era))
return dates
def get_one_date(text: str):
dates = get_date(text)
if dates:
return dates[0]
def date_western_str(text: str):
return [d.western_str() for d in get_date(text)]
def get_insurer_num(text: str):
num = None
if len(text) < 3:
return num
for keyword in ["受給", "資格者"]:
if keyword in text:
text = text[:text.index(keyword)]
matches = INSURER_NUM.findall(text)
if matches:
num = matches[0]
return num
def get_num(text: str):
matched = ANY_NUM.search(text)
if matched is None: return
return matched.group(0)
def find_one(match_func, texts):
for line in texts:
if match_func(line[-1]):
return line
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,708
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/models/utils/image.py
|
import logging
import numpy as np
import cv2
try:
import pyclipper
from shapely.geometry import Polygon
except ModuleNotFoundError:
print('Pyclipper and shapely are not installed.')
def resize_ar(img: np.ndarray, w: int, h: int, method: int =cv2.INTER_AREA):
"""
Resize an image and keep aspect ratio
"""
h0, w0 = img.shape[:2]
img_pad = np.zeros((h, w, 3), dtype=np.uint8)
scale = min(h / h0, w / w0)
h1 = int(h0 * scale)
w1 = int(w0 * scale)
img_pad[:h1, :w1] = cv2.resize(img, (w1, h1), method)
return img_pad, scale
def resize_h(img: np.ndarray, h: int, w: int, logger: logging.Logger):
"""
Resize the image to a specified height,
pad to ensure width is divisible by div
:param img: original image
:param h: target height
:param w: target width
:return: resized image with padding
"""
h0, w0 = img.shape[:2]
w1 = int(h / h0 * w0)
img_resize = cv2.resize(img, (w1, h), cv2.INTER_AREA)
img_pad = np.ones((h, w, 3), dtype=img_resize.dtype) * 200
if img_resize.shape[1] > img_pad.shape[1]:
logger.warn(f"Resized Image width {w1} > {w}, rightmost part cut off")
img_resize = img_resize[:, :img_pad.shape[1], :]
img_pad[:, :img_resize.shape[1], :] = img_resize
return img_pad, img_resize
def nms(boxes: np.ndarray, scores: np.ndarray, iou_th: float):
"""
Apply NMS to bounding boxes
:param boxes: boxes in an array with size [n*4]
:param scores: score for each box
:param iou_th: IOU threshold used in NMS
:return: boxes after NMS
"""
assert len(boxes) == len(scores)
assert boxes.shape[1] == 4
assert len(boxes.shape) == 2
assert len(scores.shape) == 1
areas = (boxes[:, 2] - boxes[:, 0] + 1) * (boxes[:, 3] - boxes[:, 1] + 1)
order = scores.argsort()[::-1]
keep = []
while order.size > 0:
keep.append(order[0])
inter_x1 = np.maximum(boxes[order[0], 0], boxes[order[1:], 0])
inter_y1 = np.maximum(boxes[order[0], 1], boxes[order[1:], 1])
inter_x2 = np.minimum(boxes[order[0], 2], boxes[order[1:], 2])
inter_y2 = np.minimum(boxes[order[0], 3], boxes[order[1:], 3])
inter_w = np.maximum(inter_x2 - inter_x1 + 1, 0)
inter_h = np.maximum(inter_y2 - inter_y1 + 1, 0)
inter_area = inter_w * inter_h
iou = inter_area / (areas[order[0]] + areas[order[1:]] - inter_area)
rest_idx = np.where(iou <= iou_th)[0]
order = order[rest_idx + 1]
final_boxes = np.array(boxes[np.array(keep)])
final_scores = np.array(scores[np.array(keep)])
return final_boxes, final_scores
def get_rect(polygons: np.ndarray, min_wh_ratio: float = 0):
if polygons.size == 0: return polygons
polygons = polygons[:, :8]
rects = []
for polygon in polygons:
pts = polygon.reshape(4, 2)
x0 = pts[:, 0].min()
x1 = pts[:, 0].max()
y0 = pts[:2, 1].mean()
y1 = pts[2:, 1].mean()
if (x1 - x0) / (y1 - y0) > min_wh_ratio:
rects.append([x0, y0, x1, y1])
rects = np.array(rects)
return rects
def get_chips(img: np.ndarray, boxes: np.ndarray):
assert len(boxes.shape) == 2 and boxes.shape[1] == 4
assert (boxes >= 0).all(), 'expect all coords to be non-negative'
chips = np.array([img[b[1]:b[3], b[0]:b[2]]for b in boxes.astype(np.int32)])
return chips
def match(img: np.ndarray, target: np.ndarray, method=cv2.TM_CCOEFF_NORMED, blur=5):
img_blur = cv2.GaussianBlur(img, (blur, blur), 0)
target_blur = cv2.GaussianBlur(target, (blur, blur), 0)
res = cv2.matchTemplate(img_blur, target_blur, method)
return res
def get_min_box(contour):
bbox = cv2.minAreaRect(contour)
angle = bbox[2] if bbox[1][0] > bbox[1][1] * 4 else 0
pts = sorted(list(cv2.boxPoints(bbox)), key=lambda x: x[0])
if pts[1][1] > pts[0][1]:
idx1, idx4 = 0, 1
else:
idx1, idx4 = 1, 0
if pts[3][1] > pts[2][1]:
idx2, idx3 = 2, 3
else:
idx2, idx3 = 3, 2
box = np.array(pts)[[idx1, idx2, idx3, idx4], ...]
ssize = min(box[:, 0::2].max() - box[:, 0::2].min(), box[:, 1::2].max() - box[:, 1::2].min())
return box, ssize, angle
def get_score(pred, contour):
h, w = pred.shape
c = contour.copy()
xmin = np.clip(np.floor(c[:, 0].min()).astype(np.int), 0, w - 1)
xmax = np.clip(np.ceil(c[:, 0].max()).astype(np.int), 0, w - 1)
ymin = np.clip(np.floor(c[:, 1].min()).astype(np.int), 0, h - 1)
ymax = np.clip(np.ceil(c[:, 1].max()).astype(np.int), 0, h - 1)
mask = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
c[:, 0] -= xmin
c[:, 1] -= ymin
cv2.fillPoly(mask, c.reshape(1, -1, 2).astype(np.int32), 1)
score = cv2.mean(pred[ymin: ymax + 1, xmin: xmax + 1], mask)[0]
return score
def unclip(box, unclip_ratio):
poly = Polygon(box)
distance = poly.area * unclip_ratio / poly.length
offset = pyclipper.PyclipperOffset()
offset.AddPath(box, pyclipper.JT_ROUND, pyclipper.ET_CLOSEDPOLYGON)
expanded = np.array(offset.Execute(distance))
return expanded
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,709
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/models/utils/general.py
|
import logging
import numpy as np
def softmax(x: np.ndarray):
"""
Apply softmax on each row
:param x: 2D array
:return: 2D array after softmax
"""
assert len(x.shape) == 2, 'Softmax expects 2D arrays'
exp_x = np.exp(x - x.max(axis=1, keepdims=True))
softmax_x = exp_x / exp_x.sum(axis=1, keepdims=True)
return softmax_x
def greedy_decode(x: np.ndarray, length: int):
"""
CTC greedy decoder
:param x: CTC encoded sequence, last label as void
:param length: sequence length
:return: decoded sequence and probability for each char
"""
lb_void = x.shape[1] - 1
encodes = x.argmax(axis=1)
probs = [x[r][i] for r, i in enumerate(encodes)]
decodes = []
dec_prob = []
positions = []
prev = -1
for i, code in enumerate(encodes[:length]):
if code != lb_void:
if prev == lb_void or code != prev:
decodes.append(code)
dec_prob.append(probs[i])
positions.append(i)
else:
if probs[i] > dec_prob[-1]:
dec_prob[-1] = probs[i]
prev = code
decodes = np.array(decodes)
dec_prob = np.array(dec_prob)
positions = np.array(positions)
return decodes, dec_prob, positions
def group_lines(texts: list, iou_threshold: float = 0.4):
grouped = []
texts = sorted(texts, key=lambda x: (x[-1][1] + x[-1][3]) / 2)
current_line = []
for text in texts:
if not current_line:
current_line.append(text)
continue
y0s = [t[-1][1] for t in current_line]
y1s = [t[-1][3] for t in current_line]
inter = np.minimum(y1s, text[-1][3]) - np.maximum(y0s, text[-1][1])
inter = np.maximum(inter, 0)
union = np.maximum(y1s, text[-1][3]) - np.minimum(y0s, text[-1][1])
iou = inter / union
if iou.mean() > iou_threshold:
current_line.append(text)
else:
current_line = sorted(current_line, key=lambda x: (x[-1][0] + x[-1][2]) / 2)
current_line.append(''.join([w[0] for w in current_line]))
grouped.append(current_line)
current_line = [text]
current_line = sorted(current_line, key=lambda x: (x[-1][0] + x[-1][2]) / 2)
current_line.append(''.join([w[0] for w in current_line]))
grouped.append(current_line)
return grouped
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,710
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/insurance_reader.py
|
from re import M
from time import process_time
import unicodedata
import pickle
import cv2
import regex as re
import numpy as np
from .base_reader import BaseReader
from info_extractor import Analyzer
from info_extractor.date import Date
def match(img, target, method=cv2.TM_CCOEFF_NORMED, blur=5):
img_blur = cv2.GaussianBlur(img, (blur, blur), 0)
res = cv2.matchTemplate(img_blur, target, method)
_, max_v, _, max_loc = cv2.minMaxLoc(res)
return max_v, max_loc
def rotate_and_validate(img,mark):
tm_threshold = 0.6
h, w = img.shape[:2]
img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
ori_max, max_loc = match(img_gray[:h//2, w//2:], mark)
if ori_max < tm_threshold:
return img, False
class SimpleReader(BaseReader):
def __init__(self, client, analyzer, main_analyzer,logger, conf):
super().__init__(client=client, logger=logger, conf=conf)
self.analyzer = analyzer
self.main_analyzer = main_analyzer
def need_rotate(self, boxes):
xs = boxes[:, 0::2]
ys = boxes[:, 1::2]
w = xs.max() - xs.min()
h = ys.max() - ys.min()
self.logger.info(f"w: {w}, h: {h}")
return w < h and w < 900 and h < 1600
def need_retry(self, texts):
self.analyzer.fit(texts)
retry = True
for k, v in self.analyzer.info.items():
if k == "JgnGak": continue
if v:
retry = False
break
return retry
def ocr(self, img):
img_res = None
img_ori = img.copy()
img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
self.info = {}
self.main_info = {}
boxes, scores = self.find_texts(img)
rotate = self.need_rotate(boxes)
print(rotate)
if rotate:
# handle orientation for card type
boxes, scores = self.find_texts(img_ori)
try:
recog_results = self.read_texts(boxes=boxes)
texts = self.group_textlines(recog_results)
except:
cv2.imwrite('debug_img.jpg',self.img)
with open('./boxes.pkl','wb') as f:
pickle.dump(boxes,f)
raise Exception('Boxes or texts are somthing wrong, please check debug_boxes.pkl and debug_img.jpg')
# simple check to see if upside down
if self.need_retry(texts):
# flip upsidedown and retry
if self.img is not None: self.img = cv2.rotate(self.img, cv2.ROTATE_180)
if self.det_img is not None: self.det_img = cv2.rotate(self.det_img, cv2.ROTATE_180)
boxes[:, 0::2] = self.img.shape[1] - 1 - boxes[:, 0::2]
boxes[:, 1::2] = self.img.shape[0] - 1 - boxes[:, 1::2]
boxes = boxes[:, [2, 3, 0, 1]]
# print(boxes)
recog_results = self.read_texts(boxes=boxes)
texts = self.group_textlines(recog_results)
if self.need_retry(texts):
# retry in another direction
new_img = cv2.rotate(self.img, cv2.ROTATE_90_CLOCKWISE)
boxes, scores = self.find_texts(new_img)
recog_results = self.read_texts(boxes=boxes)
texts = self.group_textlines(recog_results)
if self.need_retry(texts):
# flip upsidedown and retry
if self.img is not None: self.img = cv2.rotate(self.img, cv2.ROTATE_180)
if self.det_img is not None: self.det_img = cv2.rotate(self.det_img, cv2.ROTATE_180)
boxes[:, 0::2] = self.img.shape[1] - 1 - boxes[:, 0::2]
boxes[:, 1::2] = self.img.shape[0] - 1 - boxes[:, 1::2]
boxes = boxes[:, [2, 3, 0, 1]]
recog_results = self.read_texts(boxes=boxes)
texts = self.group_textlines(recog_results)
self.analyzer.fit(texts)
for l in texts:
# print(l)
print(l[-1])
print('base',self.analyzer.info)
self.main_analyzer.info.clear()
self.main_analyzer.fit(texts)
print('main',self.main_analyzer.info)
self.main_info = self.main_analyzer.info
self.info = self.analyzer.info
self.check_multi_HKJnum(texts)
return "公費"
def extract_info(self, key: str):
"""
Borrowed from mainstream insurance reader
"""
if key == 'SyuKbn':
return "公費"
else:
text = self.info.get(key, None)
if isinstance(text, Date):
print('date2str')
text = str(text)
result = {"text": text, "confidence": 1.0}
return result
def check_multi_HKJnum(self,texts):
for idx, line in enumerate(texts):
res = re.findall('(番号)',line[-1])
if res:
# print("番号発見!")
# print(f"prev line:{reader.texts[idx-1][-1]}")
line1_2 = texts[idx-1][-1]+line[-1]
hkj = re.sub('\d','',line1_2)
print(hkj)
nums=[]
if hkj =="公費負担者番号":
for txt in line[:-1]:
num = re.sub('\D','',txt[0])
if num:
print(num)
nums.append(num)
for txt in texts[idx-1][:-1]:
num = re.sub('\D','',txt[0])
if num:
print(num)
nums.append(num)
self.info['HknjaNum'] = nums
if hkj =="受給者番号":
for txt in line[:-1]:
num = re.sub('\D','',txt[0])
if num:
print(num)
nums.append(num)
for txt in texts[idx-1][:-1]:
num = re.sub('\D','',txt[0])
if num:
print(num)
nums.append(num)
self.info['Num'] = nums
# print(f"{idx}:\t",line[-1])
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,711
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/apps/__init__.py
|
"""
OCR-based applications for specific scenarios
"""
from .insurance_reader import InsuranceReader
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,712
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/server.py
|
import asyncio
import queue
import threading
import json
from pathlib import Path
import time
import cv2
import yaml
import websockets
from apps import MyNumReader, Calibrator
from apps.insurance_reader import SimpleReader
from apps.utils.image import read_scope
from info_extractor import Analyzer
from ocr2.info_extractor.main_analyzer import MainAnalyzer
from utils import get_logger, get_timestamp, handle_err_ws, load_conf, validate_json
from camera import CamClient
from model_serving import ModelClientMock
x1, y1, x2, y2 = read_scope("scope.txt")
async def serve_ocr(websocket, path):
async for data in websocket:
sess_id = get_timestamp()
img_path = data_folder / (sess_id + '.jpg')
err_save_path = log_folder / (sess_id + '_err.json')
logger.info(f'Websocket Received: {str(data)}')
if not isinstance(data, str):
await handle_err_ws(err['non-text'], err_save_path, logger, websocket)
continue
try:
json_req = json.loads(data)
except json.JSONDecodeError:
await handle_err_ws(err['non-json'], err_save_path, logger, websocket)
continue
if not validate_json(json_req):
await handle_err_ws(err['invalid-json'], err_save_path, logger, websocket)
continue
if "Scan" in json_req:
# TODO: dynamic adjustment of init brightness
if json_req["Scan"] == "Brightness":
res_json = {"Brightness": "380"}
res_str = json.dumps(res_json)
with open(str(log_folder / (sess_id + '_brightness.json')), 'w', encoding='utf-8') as f:
json.dump(res_json, f)
logger.info(res_str)
await websocket.send(res_str)
continue
t0 = time.time()
try:
# img = cap.read()
img = cv2.imread('ws_reader.jpg')
#cv2.imwrite('test.jpg',img)##########################################
logger.info(f'Capture time: {time.time() - t0 :.2f}s')
except Exception as e:
logger.error(f'Capture Error: {str(e)}')
await handle_err_ws(err['scan_err'], err_save_path, logger, websocket)
continue
if config["websocket"]["save_img"].get(json_req["Scan"].lower(), False):
ret = cv2.imwrite(str(img_path), img)
if not ret:
await handle_err_ws(err['save_err'], err_save_path, logger, websocket)
continue
logger.info('Scan done')
reader.scanned = True
try:
if json_req["Scan"] == "MyNumTest":
if calibrator.test_ocr(img):
res = "OK"
reader.load_scope()
else:
res = "NG"
res_json = {"Result": res}
res_str = json.dumps(res_json)
with open(str(log_folder / (sess_id + '_test.json')), 'w', encoding='utf-8') as f:
json.dump(res_json, f)
logger.info(res_str)
await websocket.send(res_str)
continue
elif json_req["Scan"] == "MyNumber":
syukbn = reader.ocr(img, category=json_req["Scan"])
elif json_req["Scan"] == "shuhoken":
syukbn = simple_reader.ocr(img)
reader.info = simple_reader.main_info
reader.syukbn = "主保険"
else:
syukbn = simple_reader.ocr(img)
reader.info = simple_reader.info
reader.syukbn = "公費"
logger.info(f'OCR time: {time.time() - t0 :.2f}s')
except Exception as e:
logger.error(str(e))
await handle_err_ws(err['ocr_err'], err_save_path, logger, websocket)
continue
res_json = {"Category": "NA", "Syukbn": syukbn, "ImagePath": str(img_path)}
res_str = json.dumps(res_json)
#with open(str(log_folder / (sess_id + '_scan.json')), 'w', encoding='utf-8') as f:
# json.dump(res_json, f)
logger.info(f'OCR total: {time.time() - t0 :.2f}s')
logger.info(res_str)
await websocket.send(res_str)
if 'Patient' in json_req or 'MyNumber' in json_req:
if not reader.scanned:
await handle_err_ws(err['no_scan'], err_save_path, logger, websocket)
continue
reader.scanned = False
print(simple_reader.info)
print(reader.info)
res_json = {}
for meta_k, meta_v in json_req.items():
res_json[meta_k] = {}
if isinstance(meta_v, dict):
for field in meta_v:
res_json[meta_k][field] = reader.extract_info(field)
print(field, res_json[meta_k][field],res_json[meta_k][field]['text'],type(res_json[meta_k][field]['text']))
res_str = json.dumps(res_json)
#with open(str(log_folder / (sess_id + '_info.json')), 'w', encoding='utf-8') as f:
# json.dump(res_json, f)
logger.info(res_str)
await websocket.send(res_str)
# config
err = load_conf("config/err.yaml")
config = load_conf("config/api.yaml")
cam_conf = load_conf("config/camera.yaml")
mynum_conf = load_conf("config/mynum_reader.yaml")
insurance_conf = load_conf("config/insurance_reader.yaml")
calib_conf = load_conf("config/calibrator.yaml")
#miscs
logger = get_logger(config['logger'])
data_folder = Path(config['websocket']['data_path'])
log_folder = data_folder / 'backend_res'
if not log_folder.exists():
log_folder.mkdir(parents=True, exist_ok=True)
# ocr
cap = CamClient(cam_conf)
client = ModelClientMock(logger=logger)
reader = MyNumReader(logger=logger, client=client, conf=mynum_conf)
simple_reader = SimpleReader(logger=logger, client=client, analyzer=Analyzer(),main_analyzer=MainAnalyzer(), conf=insurance_conf)
calibrator = Calibrator(logger=logger, client=client, conf=calib_conf)
# start server
ocr_ip = config["websocket"]["ocr"]["ip"]
ocr_port = config["websocket"]["ocr"]["port"]
logger.info(f"Starting OCR server at ws://{ocr_ip}:{ocr_port}")
ocr_server = websockets.serve(serve_ocr, ocr_ip, ocr_port)
asyncio.get_event_loop().run_until_complete(ocr_server)
asyncio.get_event_loop().run_forever()
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,713
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/models/dense8_armnn.py
|
from pathlib import Path
import pyarmnn as ann
from .dense8_base import Dense8Base
class Dense8ArmNN(Dense8Base):
"""
ARMNN wrapper for Dense8 inference
"""
def __init__(self, model_path, runtime, logger, **kwargs):
super().__init__(logger, **kwargs)
self.parser = ann.ITfLiteParser()
netIdx = 0
if Path(model_path).exists():
self.net = self.parser.CreateNetworkFromBinaryFile(model_path)
else:
self.net = getattr(self.parser, "Create" + model_path)()
if "192" in model_path: netIdx = 1
if "1024" in model_path: netIdx = 2
if "1408" in model_path: netIdx = 3
self.graph_id = 0
self.nodes_in = self.parser.GetSubgraphInputTensorNames(self.graph_id)
assert len(self.nodes_in) == 1, f'{len(self.nodes_in)} inputs found, 1 expected'
self.input_binding_info = self.parser.GetNetworkInputBindingInfo(self.graph_id, self.nodes_in[0])
self.nodes_out = self.parser.GetSubgraphOutputTensorNames(self.graph_id)
assert len(self.nodes_out) == 1, f'{len(self.nodes_out)} outputs found, 1 expected'
self.output_binding_infos = [self.parser.GetNetworkOutputBindingInfo(self.graph_id, n) for n in self.nodes_out]
self.output_tensors = ann.make_output_tensors(self.output_binding_infos)
self.infer_idx = runtime.get_infer_idx()
self.runtime = runtime.runtime
backend = kwargs.get('backend', 'CpuAcc')
self.logger.info(f'Dense8 uses ARMNN backend: {backend}')
self.backend = ann.BackendId(backend)
opt_options = ann.OptimizerOptions(backend=="GpuAcc", False, False, False, netIdx)
self.logger.info(f'Dense8 FP16 Turbo mode: {opt_options.m_ReduceFp32ToFp16}')
opt_net, messages = ann.Optimize(self.net, [self.backend], self.runtime.GetDeviceSpec(), opt_options)
self.net_id, _ = self.runtime.LoadNetwork(opt_net)
self.input_shape = tuple(self.input_binding_info[1].GetShape())
logger.info(f"Dense input shape: {self.input_shape}")
self.input_h = self.input_shape[1]
self.input_w = self.input_shape[2]
def infer_sync(self, img, num_only=False):
feed = self.preprocess(img, nchw=False)[0]
self.logger.debug("Dense8 preprocess done")
input_tensors = ann.make_input_tensors([self.input_binding_info], [feed])
self.logger.debug("Dense8 input ready")
self.runtime.EnqueueWorkload(self.net_id, input_tensors, self.output_tensors)
self.logger.debug("Dense8 inference done")
logits = ann.workload_tensors_to_ndarray(self.output_tensors)[0]
self.logger.debug("Dense8 output ready")
codes, probs, positions = self.parse_result(logits, num_only)
self.logger.debug("Dense8 output parsed")
return codes, probs, positions
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,714
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/camera/__init__.py
|
from .client import CamClient
from .server import CamServer
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,715
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/utils/openvino.py
|
"""Helper functions for OpenVINO"""
from pathlib import Path
from openvino.inference_engine import IECore
def get_openvino_dir() -> Path:
"""Gets root dir of OpenVINO."""
home_install = Path.home()/'intel/openvino/'
sys_install = Path('/opt/intel/openvino/')
if sys_install.exists():
return sys_install
return home_install
def get_ie_core(dev: str) -> IECore:
"""Gets IRCore for OpenVINO inference.
Args:
dev: Name of inference hardware.
Returns:
An IECore object.
"""
ie_core = IECore()
if dev == 'CPU':
ext_path = (get_openvino_dir() /
'inference_engine/lib/intel64/libcpu_extension_sse4.so')
if ext_path.exists():
ie_core.add_extension(str(ext_path), dev)
return ie_core
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,716
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/models/ctpnp_armnn.py
|
import numpy as np
import pyarmnn as ann
from .ctpnp_base import CTPNPBase
class CTPNP_ARMNN(CTPNPBase):
def __init__(self, model_path: str, runtime, logger, **kwargs):
super().__init__(logger, **kwargs)
if model_path.endswith('.tflite'):
self.parser = ann.ITfLiteParser()
self.net = self.parser.CreateNetworkFromBinaryFile(model_path)
else:
raise NotImplementedError('Only tflite is supported')
self.graph_id = 0
self.nodes_in = self.parser.GetSubgraphInputTensorNames(self.graph_id)
assert len(self.nodes_in) == 1, f'{len(self.nodes_in)} inputs found, 1 expected'
self.input_binding_info = self.parser.GetNetworkInputBindingInfo(self.graph_id, self.nodes_in[0])
self.nodes_out = self.parser.GetSubgraphOutputTensorNames(self.graph_id)
assert len(self.nodes_out) == 3, f'{len(self.nodes_out)} outputs found, 3 expected'
self.output_binding_infos = [self.parser.GetNetworkOutputBindingInfo(self.graph_id, n) for n in self.nodes_out]
self.output_tensors = ann.make_output_tensors(self.output_binding_infos)
self.infer_idx = runtime.get_infer_idx()
self.runtime = runtime.runtime
self.backend = ann.BackendId(kwargs.get('backend', 'CpuAcc'))
self.logger.info('CTPNP uses ARMNN backend:', self.backend)
opt_options = ann.OptimizerOptions()
if self.backend == 'GpuAcc':
opt_options.m_ReduceFP32ToFp16 = True
opt_net, messages = ann.Optimize(self.net, [self.backend], self.runtime.GetDeviceSpec(), opt_options)
self.net_id, _ = self.runtime.LoadNetwork(opt_net)
self.input_shape = tuple(self.input_binding_info[1].GetShape())
self.input_h = self.input_shape[1]
self.input_w = self.input_shape[2]
def infer_sync(self, img: np.ndarray, suppress_lines: bool = True):
feed = self.preprocess(img, nchw=False)[0]
input_tensors = ann.make_input_tensors([self.input_binding_info], [feed])
import time
t0 = time.time()
self.runtime.EnqueueWorkload(self.net_id, input_tensors, self.output_tensors)
# print(f'ctpnp enqueue time: {(time.time() - t0):.2f}s')
cls_pred, cnt_pred, box_pred = ann.workload_tensors_to_ndarray(self.output_tensors)
# exp is not supported in ARMNN 20.02
box_pred = np.exp(box_pred)
lines = self.parse_result(cls_pred, cnt_pred, box_pred, suppress_lines=suppress_lines)
return lines
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,717
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/utils/__init__.py
|
from .check import ensure_type, valid_path, validate_json
from .log import get_logger, get_timestamp, handle_err_ws
from .image import crop, crop_print
from .conf import load_conf
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,718
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/finders/date.py
|
"""Finder to extract all dates from multiple lines of text"""
from typing import List, Any
from copy import deepcopy
import yaml
import numpy as np
from .. import match
from .. import extract
from ..match import score
class DatesFinder(yaml.YAMLObject):
"""Finder to extract multiple dates from multiple text lines output by OCR.
Disclaimer:
This finder was originally designed to address the issue that different kinds
of dates may be extracted from the same excerpt. However, THIS IS NOT MEANT
TO BE A FINAL SOLUTION FOR DATE EXTRACTION due to limited time and testing
data. If a maintainer finds out some code does not make sense, probably it's
because the code does not make sense indeed, and such a maintainer is
encouraged to modify or totally reimplement this finder.
Another problem that can be addressed, but has NOT been addressed is
inconsistency between extracted dates. e.g. YukoEdYmd is earlier than
YukoStYmd. You are encouraged to implement a check for this problem
if you ovserve such inconsistency in tests.
Typical usage example:
>>> match_methods = {
"Birthday": "birthday_match",
"YukoEdYmd": "valid_until_match",
"YukoStYmd": "valid_from_match",
"KofuYmd": "kofu_match",
}
>>> finder = DatesFinder(
match_methods=match_methods,
extract_method="get_date"
)
>>> texts = [
["生年月日平成1年2月3日"],
["有効開始日令和元年1月2日有効終了日令和2年1月2日"],
["令和元年1月1日交付"]
]
>>> dates = finder.extract(texts)
>>> print(dates["Birthday"])
19890203
>>> print(dates["YukoStYmd"])
20190102
>>> print(dates["YukoEdYmd"])
20200102
>>> print(dates["KofuYmd"])
20190101
Args:
match_methods: Name of the function for pattern matching, which has to be
defined in `..match`
extract_method: Name of the function for information extraction, which has
to be defined in `..extract`
"""
yaml_tag = u'!DatesFinder'
def __init__(self, match_methods: str, extract_method: str):
self.match_methods = match_methods
self.extract_method = extract_method
self.scores = {}
self.texts = {}
self.info = {}
def _score(self, texts: List[List[Any]]):
"""Scores each textline for each kind of date to extract.
Args:
texts: OCR results in a list, each element of each has also to be a
list, each element of which is the text for each detected line.
"""
for tag, match_func in self.match_methods.items():
# only look above and below for birth dates
self.scores[tag], self.texts[tag] = score(
match_func=getattr(match, match_func),
texts=texts,
no_ext=(tag != "Birthday")
)
# if YukoEdYmd found within the first 2 lines, make an exception to look below
if tag == "YukoEdYmd" and sum(self.scores[tag][:2]) == 1:
self.scores[tag], self.texts[tag] = score(
match_func=getattr(match, match_func),
texts=texts,
no_ext=False
)
def extract(self, texts: List[List[Any]]) -> dict:
"""Extracts all kinds of dates from text lines when possible.
Args:
texts: OCR results in a list, each element of each has also to be a
list, each element of which is the text for each detected line.
Returns:
A dict of extracted dates
"""
self.texts = {}
self.info = {}
self._score(texts)
# extract dates from lines with positive score for any key
extract_f = getattr(extract, self.extract_method)
dates_all = {}
for (tag, lines), (_, scores) in zip(
self.texts.items(),
self.scores.items()
):
dates_all[tag] = [extract_f(line) if score > 0 else [] for score, line in zip(scores, lines)] #pylint: disable=line-too-long
# date match NMS
for i in range(len(texts)):
key_keep, suppress = None, False
for key, cur_score in self.scores.items():
if cur_score[i] < 2:
continue
if suppress:
# more than 1 line with score > 1
suppress = False
break
key_keep = key
suppress = True
if suppress:
for key, cur_dates in dates_all.items():
if key == key_keep or not cur_dates: continue
for idx, (dates1, dates2) in enumerate(zip(
cur_dates,
dates_all[key_keep]
)):
dates_all[key][idx] = [d1 for d1 in dates1 if d1 not in dates2]
# suppress YukoStYmd when YukoEdYmd and KofuYmd matched on the same line
for idx, dates in enumerate(dates_all["YukoEdYmd"]):
if (self.scores["YukoStYmd"][idx] and
self.scores["KofuYmd"][idx] and
len(dates) < 3):
self.scores["YukoStYmd"][idx] = 0
dates_all["YukoStYmd"][idx].clear()
# handle 2 dates in the same line
for idx, dates in enumerate(dates_all["YukoEdYmd"]):
if (len(dates) == 2 and
self.scores["YukoStYmd"][idx] > 0 and
self.scores["KofuYmd"][idx] == 0):
self.info["YukoStYmd"], self.info["YukoEdYmd"] = dates
if str(self.info["YukoStYmd"]) > str(self.info["YukoEdYmd"]):
self.info["YukoStYmd"], self.info["YukoEdYmd"] = self.info["YukoEdYmd"], self.info["YukoStYmd"] #pylint: disable=line-too-long
# assign dates recursively
for th in np.arange(np.max(list(self.scores.values())), 0, -1):#pylint: disable=too-many-nested-blocks
scores_prev = {}
while not all([np.all(scores_prev.get(k, None) == v) for k, v in self.scores.items()]):#pylint: disable=line-too-long
scores_prev = deepcopy(self.scores)
for key in self.scores:
if self.info.get(key, None) is not None: continue
val_max, idx_max = self.scores[key].max(), self.scores[key].argmax()
if (val_max >= th and
len(self.scores[key][self.scores[key] == val_max]) == 1 and
len(dates_all[key][idx_max]) == 1):
self.info[key] = dates_all[key][idx_max][0]
# pop out used date
for other_key in set(self.scores.keys()) - set(key):
other_dates = dates_all[other_key][idx_max]
if other_dates:
new_dates = [d for d in other_dates if str(d) != str(self.info[key])] #pylint: disable=line-too-long
dates_all[other_key][idx_max] = new_dates
# handle yukostymd and yukoedymd in the same line
if "YukoStYmd" not in self.info and "YukoEdYmd" not in self.info:
idx_from = self.scores["YukoStYmd"].argmax()
idx_until = self.scores["YukoEdYmd"].argmax()
dates_from = dates_all["YukoStYmd"][idx_from]
dates_until = dates_all["YukoEdYmd"][idx_until]
if str(dates_from) == str(dates_until) and len(dates_from) == 2:
self.info["YukoStYmd"], self.info["YukoEdYmd"] = dates_from
# handle YukoEdYmd and KofuYmd in the same line
if (self.info.get("YukoEdYmd", None) is None and
self.info.get("KofuYmd", None) is None):
for idx in range(len(self.scores["YukoEdYmd"])):
if (self.scores["KofuYmd"][idx] > 0 and
len(dates_all["YukoEdYmd"][idx]) == 2 and
len(dates_all["KofuYmd"][idx]) == 2):
self.info["KofuYmd"], self.info["YukoEdYmd"] = dates_all["KofuYmd"][idx] #pylint: disable=line-too-long
# make sure KofuYmd is earlier than YukoEdYmd
if str(self.info["KofuYmd"]) > str(self.info["YukoEdYmd"]):
self.info["KofuYmd"], self.info["YukoEdYmd"] = self.info["YukoEdYmd"], self.info["KofuYmd"] #pylint: disable=line-too-long
for key in self.scores:
if self.info.get(key, None) is None:
for idx in (-self.scores[key]).argsort(kind="mergesort"):
if dates_all[key][idx]:
# use the earliest date for birthday
if key == "Birthday":
dates_all[key][idx] = sorted(dates_all[key][idx], key=str)
self.info[key] = dates_all[key][idx].pop(0)
break
for tag in self.match_methods:
if tag not in self.info:
self.info[tag] = None
return self.info
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,719
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/finders/valid_date.py
|
import yaml
from ..match import valid_from_match, valid_until_match
from .. import match
from .. import extract
class ValidDateFinder(yaml.YAMLObject):
yaml_tag = u'!ValidDateFinder'
def __init__(self):
self.info = {}
self.date_pairs = []
def assign_dates(self, text, dates):
def extract_same_line(self, texts):
for i, text in enumerate(texts):
if len(text.dates) == 2 and valid_from_match(text.all_text):
date_pairs.append(tuple(text.dates))
def extract_separate_lines(self, texts):
for i, text in enumerate(texts):
if valid_from_match(text.all_text) and len(text.dates) == 1:
if len(texts[i + 1].dates) == 1:
self.date_pairs.append((text.dates[0], texts[i + 1].dates[0]))
if len(texts[i + 1].dates) == 0 and len(texts[i + 2].dates) == 1:
self.date_pairs.append((text.dates[0], texts[i + 2].dates[0]))
def assign_dates(self):
def extract(self, texts):
self.info.clear()
self.extract_same_line(texts)
self.extract_seperate_lines(texts)
self.assign_dates()
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,720
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/utils/general.py
|
import numpy as np
def get_date_roi(mark_x, mark_y, w, h):
x1 = max(mark_x - 790, 0)
x2 = min(mark_x + 50, w - 1)
y1 = min(mark_y + 245, h - 1)
y2 = min(mark_y + 325, h - 1)
box = np.array([x1, y1, x2, y2])
return box
def get_num_roi(mark_x, mark_y, w, h):
x1 = max(mark_x - 900, 0)
x2 = max(mark_x - 740, 0)
y1 = min(mark_y + 755, h - 1)
y2 = min(mark_y + 855, h - 1)
box = np.array([x1, y1, x2, y2])
return box
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,721
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/utils/log.py
|
from pathlib import Path
import sys
import logging
import json
from datetime import datetime
from . import valid_path
def get_logger(config):
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger()
logger.handlers = []
logger.setLevel(getattr(logging, config.get('level', 'DEBUG')))
# stream
stream_handler = logging.StreamHandler(stream=sys.stdout)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
# file
log_path = config.get('path', None)
if log_path is not None:
log_folder = Path(log_path)
if not log_folder.exists():
log_folder.mkdir(parents=True, exist_ok=True)
file_handler = logging.FileHandler(f"{log_folder}/{get_timestamp()}_scanner.log")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
def get_timestamp():
timestamp = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
return timestamp
def handle_err(err, save_path, logger):
save_path = valid_path(save_path)
with open(str(save_path), 'w', encoding='utf-8') as f:
json.dump(err, f)
logger.error(f'[{err["ErrCode"]}] {err["ErrMsg"]}')
err_str = json.dumps(err)
return err_str
async def handle_err_ws(err, save_path, logger, websocket):
err_str = handle_err(err, save_path, logger)
await websocket.send(err_str)
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,722
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/utils/text.py
|
"""Helper functions for text processing"""
from typing import List, Any
import unicodedata
import regex as re
import numpy as np
NUM_FIX = {
'l': '1',
'i': '',
'Ⅰ': '',
't': '1',
'」': '1',
'「': '1',
'丁': '1',
'亅': '1',
'}': '1',
'{': '1',
'o': '0',
's': '5',
'g': '9',
}
YMD = re.compile(r"(年月日){e<2}")
def fix_num(text: str) -> str:
"""Fix incorrectly recognized numbers
Args:
text: a string
Returns:
A string, where certain incorrectly recognized numbers are corrected
"""
use_fix = False
if YMD.search(text) is not None:
use_fix = True
if '番号' in text or '記号' in text:
use_fix = True
if len(text) == 2 and text[1] == '割':
use_fix = True
if use_fix:
for k in NUM_FIX:
text = text.replace(k, NUM_FIX[k])
return text
def fuzzy_match(target: str, text: str, e_max: int = 2) -> bool:
"""Match a keyword in text with torlerance
Args:
target: keyword to match
text: text where to match the keyword
e_max: # of mismatched chars that leads to a False return, default: 2
Returns:
A bool, True if the match is successful
"""
pattern = re.compile("(" + target + "){e<" + str(e_max) + "}")
if pattern.search(text) is not None:
return True
return False
def clean_half_width(texts: List[List[Any]]) -> List[List[Any]]:
"""Cleans text and converts to half-width.
Args:
texts: A list of OCR results, each element of which is also a list
containing all information of one line.
Returns:
A list with the same structure as `texts` but cleaned text.
"""
for idx, line in enumerate(texts):
# remove nums that are too close
for idx_w, (text, probs, positions, _) in enumerate(line[:-1]):
x_dist = positions[1:] - positions[:-1]
close_indices = np.where(x_dist < 32)
if close_indices[0].size > 0 and all([not c.isdigit() for c in text]):
for idx_m in close_indices[0]:
if (unicodedata.normalize('NFKC', text[idx_m]) ==
unicodedata.normalize('NFKC', text[idx_m + 1])):
texts[idx][idx_w][0] = text[:idx_m + 1] + text[idx_m+2:]
texts[idx][idx_w][1][idx_m:idx_m+2] = [probs[idx_m]]
texts[idx][idx_w][2][idx_m:idx_m+2] = [positions[idx_m]]
texts[idx][-1] = ''.join([l[0] for l in texts[idx][:-1]])
texts[idx][-1] = unicodedata.normalize('NFKC', fix_num(line[-1])).upper()
return texts
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,723
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/utils/conf.py
|
import yaml
def load_conf(path, encoding="utf-8"):
with open(path, encoding=encoding) as f:
config = yaml.safe_load(f)
return config
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,724
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/utils/general.py
|
"""General helper functions for OCR"""
from typing import List, Any
import numpy as np
def group_lines(
texts: List[List[Any]],
iou_threshold: float = 0.4
) -> List[List[Any]]:
"""Groups texts with bounding boxes in lines.
Args:
texts: A list of OCR result, each element of which is also a list of
[text, probability, position, bouding_box]
iou_threshold: Threshold for IOU in vertical direction to determine if
two bounding boxes belong to the same line.
Returns:
A list of lists of bouding boxes belonging to the same line.
"""
grouped = []
texts = sorted(texts, key=lambda x: (x[-1][1] + x[-1][3]) / 2)
current_line = []
for text in texts:
if not current_line:
current_line.append(text)
continue
y0s = [t[-1][1] for t in current_line]
y1s = [t[-1][3] for t in current_line]
inter = np.minimum(y1s, text[-1][3]) - np.maximum(y0s, text[-1][1])
inter = np.maximum(inter, 0)
union = np.maximum(y1s, text[-1][3]) - np.minimum(y0s, text[-1][1])
iou = inter / union
if iou.mean() > iou_threshold:
current_line.append(text)
else:
current_line = sorted(current_line, key=lambda x: (x[-1][0] + x[-1][2]) / 2)
current_line.append(''.join([w[0] for w in current_line]))
grouped.append(current_line)
current_line = [text]
current_line = sorted(current_line, key=lambda x: (x[-1][0] + x[-1][2]) / 2)
current_line.append(''.join([w[0] for w in current_line]))
grouped.append(current_line)
return grouped
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,725
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/textline.py
|
from ..extract import get_date, get_num, get_insurer_num
class Word:
def __init__(self, word):
self.text = word[0]
self.probs = word[1]
self.positions = word[2]
self.bbox = word[3].astype(int)
def prob_lower_than(self, threshold, method="any"):
res = self.probs < threhold
return getattr(res, method)()
class TextLine:
def __init__(self, text):
words, self.all_text = text[:-1], text[-1]
self.words = [Word(w) for w in words]
self.dates = get_date(self.all_text)
self.any_num = get_num(self.all_text)
self.hknja_num = get_insurer_num(self.all_text)
self.len = len(self.all_text)
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,726
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/finders/__init__.py
|
from .simple import SimpleFinder
from .date import DatesFinder
from .wide import WideFinder
from .jgngak import JgnGakFinder
from .rouftnkbn import RouFtnKbnFinder
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,727
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/finders/jgngak.py
|
import yaml
from ..re_pattern import DEDUCTIBLE_TAG, DEDUCTIBLE_AMT, DEDUCTIBLE_WITH_TAG, DEDUCTIBLE_TAGS
class JgnGakFinder(yaml.YAMLObject):
yaml_tag = u'!JgnGakFinder'
def _get_amount(self, line):
limit = DEDUCTIBLE_AMT.findall(line[-1])
if limit:
self.info['JgnGak'] = limit[0].replace('o', '0')
if self.info['JgnGak'][0] == '0' and len(self.info["JgnGak"]) > 1:
self.info['JgnGak'] = '1' + self.info['JgnGak']
return self.info['JgnGak']
def _get_multi(self, texts):
flags = [True for _ in range(len(DEDUCTIBLE_TAGS))]
res = ""
for line in texts:
for idx, (tag, pattern, need) in enumerate(zip(DEDUCTIBLE_TAGS, DEDUCTIBLE_WITH_TAG, flags)):
if not need: continue
matched = pattern.findall(line[-1])
#print(line[-1], matched)
if matched and matched[0] is not None:
res += tag + " " + matched[0].replace('o', '0') + ";"
flags[idx] = False
return res
def extract(self, texts):
self.info = {}
multi_res = self._get_multi(texts)
#print("multi res:", multi_res)
if multi_res: return multi_res
for line in texts:
if DEDUCTIBLE_TAG.search(line[-1]):
amount = self._get_amount(line)
if amount: return amount
print('JgnGak with tag not found, search yen in each line')
for line in texts:
amount = self._get_amount(line)
if amount: return amount
if "JgnGak" not in self.info:
self.info["JgnGak"] = None
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,728
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/calibrator.py
|
import numpy as np
import cv2
import regex as re
from .base_reader import BaseReader
from .utils.image import box_crop, save_scope
class Calibrator(BaseReader):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.scope = None
conf = kwargs["conf"]
self.matches = conf["match"]
self.crop_margin = conf["crop_margin"]
def flip(self, boxes, img):
if np.sum(boxes[:, 3] < img.shape[0] // 2) < boxes.shape[0] * 0.7:
self.img = cv2.rotate(self.img, cv2.ROTATE_180)
self.det_img = cv2.rotate(self.det_img, cv2.ROTATE_180)
boxes[:, 1::2] = img.shape[0] - boxes[:, 1::2]
boxes[:, 0::2] = img.shape[1] - boxes[:, 0::2]
boxes_rot = boxes.copy()
boxes_rot[:, :2], boxes_rot[:, 2:] = boxes[:, 2:], boxes[:, :2]
boxes = boxes_rot
return boxes
def test_ocr(self, img):
boxes, scores = self.find_texts(img)
img, self.scope = box_crop(boxes, img, self.crop_margin)
save_scope(self.scope, "scope.txt")
boxes, scores = self.find_texts(img)
boxes = self.flip(boxes, img)
recog_results = self.read_texts(boxes=boxes)
textlines = self.group_textlines(recog_results)
all_text = "".join([l[-1] for l in textlines])
for key_phrase in self.matches:
if re.search(str(key_phrase) + "{e<2}", all_text) is None:
print(key_phrase, all_text)
return False
return True
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,729
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/analyzer.py
|
from pathlib import Path
import numpy as np
import yaml
#from .textline import TextLine
from .finders import SimpleFinder, DatesFinder, WideFinder, JgnGakFinder, RouFtnKbnFinder
from .match import kohi_num_match, insurer_match
from .extract import find_one, get_num, get_date
from .re_pattern import KIGO
def load_finder(tag, category):
path = Path(__file__).resolve().parent / "presets" / category / (tag.lower() + ".yaml")
with open(str(path)) as f:
obj = yaml.load(f, Loader=yaml.Loader)
return obj
date_tags = [
"入院",
"入院外",
"外来",
"通院",
"調剤",
"無",
"1割"
]
class Analyzer:
def __init__(self):
self.texts = []
self.info = {}
self.config = {
"HknjaNum": "wide_finder",
"Num": "simple_finder",
#"Birthday": "birthday_finder",
#("YukoStYmd", "YukoEdYmd"): "valid_date_finder",
("Birthday", "YukoStYmd", "YukoEdYmd", "KofuYmd"): "dates_finder",
"JgnGak": JgnGakFinder(),
"RouFtnKbn": RouFtnKbnFinder(),
}
self.finders = {}
for tag, cat in self.config.items():
if not isinstance(cat, str):
self.finders[tag] = cat
continue
if isinstance(tag, str):
self.finders[tag] = load_finder(tag, cat)
elif isinstance(tag, tuple):
self.finders[tag] = load_finder(cat, cat)
def fit(self, texts):
#self.texts = [TextLine(t) for t in texts]
self.texts = texts
self.info = {}
for tag in self.finders:
if isinstance(tag, str):
self.info[tag] = self.finders[tag].extract(texts)
if isinstance(tag, tuple):
for k, v in self.finders[tag].extract(texts).items():
self.info[k] = v
# specil handling of hknjanum and num on the same line
if self.info.get("HknjaNum", None) is None or self.info.get("Num", None) is None:
for idx, line in enumerate(texts[:5]):
ret1, text1 = insurer_match(line[-1])
ret2, text2 = kohi_num_match(line[-1])
#print(line[-1], ret1, ret2)
if ret1 and ret2 and idx + 1 < len(texts):
next_line = texts[idx + 1][-1]
if next_line.isdigit():
self.info["HknajaNum"] = next_line[:8]
self.info["Num"] = next_line[8:]
# special handling for kigo
if "Kigo" not in self.info:
self.info["Kigo"] = None
for line in texts:
for pattern in KIGO:
match = pattern.findall(line[-1])
if match and match[0] is not None:
self.info["Kigo"] = match[0]
# special handling for multiple dates
froms = []
untils = []
tags = []
for idx, line in enumerate(texts):
has_from = "から" in line[-1] or (len(line[-1]) > 2 and "か" == line[-1][-2])
has_until = "迄" in line[-1] or "まで" in line[-1]
if not has_from and not has_until: continue
dates = get_date(line[-1])
if has_from and has_until and len(dates) == 2:
froms.append((idx, dates[0]))
untils.append((idx, dates[1]))
continue
if has_from and len(dates) == 1:
froms.append((idx, dates[0]))
if has_until and len(dates) == 1:
untils.append((idx, dates[0]))
#print(texts[0][-1])
#print(froms, untils)
if not (len(untils) > 1 and len(froms) > 1): return
new_st = ""
new_ed = ""
for (idx_f, date_f), (idx_u, date_u) in zip(froms, untils):
start = max(0, idx_f - 2, idx_u - 2)
end = min(len(texts) - 1, idx_f + 2, idx_u + 2)
for cidx in range(start, end + 1):
for tag in date_tags:
if tag in texts[cidx][-1].replace("憮", "無"):
new_st += tag + " " + str(date_f) + ";"
new_ed += tag + " " + str(date_u) + ";"
texts[cidx][-1].replace(tag, "")
if new_st and new_ed:
self.info["YukoStYmd"] = new_st
self.info["YukoEdYmd"] = new_ed
def get(self, tag):
return self.info.get(tag, None)
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,730
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/finders/__init__.py
|
"""Finder classes that extract key information from OCR results.
Instead of indpendent usage, finders are typically used inside an analyzer.
"""
from .simple import SimpleFinder
from .date import DatesFinder
from .wide import WideFinder
from .jgngak import JgnGakFinder
from .rouftnkbn import RouFtnKbnFinder
from .kigo_num import KigoNumFinder
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,731
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/models/.ipynb_checkpoints/dbnet_base-checkpoint.py
|
import numpy as np
import cv2
from .utils.image import resize_ar, get_min_box, get_score, unclip, get_rect
class DBNet:
def __init__(self,
logger,
threshold: float = 0.3,
box_th: float = 0.5,
max_candidates: int = 1000,
unclip_ratio: float = 2,
min_size: int = 3):
self.logger = logger
self.threshold = threshold
self.box_th = box_th
self.max_candidates = max_candidates
self.unclip_ratio = unclip_ratio
self.min_size = min_size
def preprocess(self, img: np.ndarray):
img, self.scale = resize_ar(img, self.input_w, self.input_h)
self.img = img.copy()
img = img[np.newaxis, ...].astype(np.float32)
return img
def parse_result(self, result: np.ndarray):
result = result[0, ..., 0]
mask = result > self.threshold
h, w = mask.shape
contours, _ = cv2.findContours((mask * 255).astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
n_contours = min(len(contours), self.max_candidates)
boxes = []
scores = []
rects = []
for idx, contour in enumerate(contours[:n_contours]):
c = contour.squeeze(1)
pts, sside = get_min_box(c)
if sside < self.min_size:
continue
score = get_score(result, c)
if self.box_th > score:
continue
c = unclip(pts, unclip_ratio=self.unclip_ratio).reshape(-1, 1, 2)
pts, sside = get_min_box(c)
if sside < self.min_size + 2:
continue
pts[:, 0] = np.clip(np.round(pts[:, 0]), 0, w)
pts[:, 1] = np.clip(np.round(pts[:, 1]), 0, h)
boxes.append(pts)
scores.append(score)
boxes = np.array(boxes)
scores = np.array(scores)
boxes /= self.scale
boxes = get_rect(boxes)
return boxes, scores
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,732
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/analyzer_base.py
|
"""A base class for analyzers.
This class implements the common methods shared among all analyzers.
"""
from pathlib import Path
from typing import Any, Union
import yaml
def load_finder(tag: str, category: str) -> Any:
"""Loads a predefined finder from YAML
Args:
tag: A string indicating what item the finder extracts
category: A string indicating the type of the finder.
e.g. wide_finder
Returns:
A finder with an extract method that can be used in
`AnalyzerBase._finder_fit`.
"""
path = (Path(__file__).resolve().parent /
"presets" / category / (tag.lower() + ".yaml"))
with open(str(path)) as f:
obj = yaml.load(f, Loader=yaml.Loader)
return obj
class AnalyzerBase:
"""Base class for all analyzer classes.
Args:
config: a dict specifying to use which finder for which item
"""
def __init__(self, config: dict):
self.texts = []
self.info = {}
self.config = config
self.finders = {}
for tag, cat in self.config.items():
if not isinstance(cat, str):
self.finders[tag] = cat
continue
if isinstance(tag, str):
self.finders[tag] = load_finder(tag, cat)
elif isinstance(tag, tuple):
self.finders[tag] = load_finder(cat, cat)
def _finder_fit(self, texts):
self.texts = texts
self.info = {}
for tag in self.finders:
if isinstance(tag, str):
self.info[tag] = self.finders[tag].extract(texts)
if isinstance(tag, tuple):
for k, v in self.finders[tag].extract(texts).items():
self.info[k] = v
def _have(self, tag):
return self.info.get(tag, None) is not None
def get(self, tag: str) -> Union[str, None]:
"""Gets extracted information for a certain item.
Args:
tag: Name of the item to get.
Returns:
A string if required item was extracted sucessfully,
`None` otherwise.
"""
return self.info.get(tag, None)
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,733
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/match.py
|
"""Functions to determine if there is certain information in text"""
from typing import Tuple, Union, Callable, List
import numpy as np
import regex as re
from .extract import get_date, get_insurer_num
from .re_pattern import BIRTHDAY, INSURER, KOHI_NUM, VALID_FROM, UNTIL_FIX
from .re_pattern import VALID_UNTIL, KOFU_FIX, KOFU, SKKGET, PERCENT, BRANCH
def match_one(patterns: list, text: str) -> Tuple[bool, Union[str, None]]:
"""Matches given patterns one by one in text, and returns the first matched.
Args:
patterns: A list of compiled regex expression
text: Text to match
Returns:
`(success, res)`, where `success` is a boolean indicating if there is
anything matched, and res is a `regex.Match` if anything matched, and
`None` otherwise.
"""
for p in patterns:
matched = p.search(text)
if matched is not None:
return True, matched
return False, None
def birthday_match(text: str) -> Tuple[bool, str]:
"""Checks if text contains a birth date.
Args:
text: Text to check
Returns:
`(success, text)`, where `success` is `True` if there is a birth date,
`False` if not. `text` is exactly the same input argument.
"""
if BIRTHDAY.search(text):
return True, text
return False, text
def insurer_match(text: str) -> Tuple[bool, Union[str, None]]:
"""Checks if text contains an insurer number.
Args:
text: Text to check
Returns:
`(success, text)`, where `sucess` is `True` if matched, `False` if not,
and `text` is text truncated from the matched pattern if matched, `None`
if not.
e.g.
>>> insurer_match("123456保険者番号87654321")
True 保険者番号87654321
"""
# get rid of phone number
text = re.sub(r"\d+\(\d+\)\d+", "", text)
ret, matched = match_one(INSURER, text)
if ret:
print(matched)
# check right side at first
if matched and get_insurer_num(text[matched.span()[0]:]):
return ret, text[matched.span()[0]:]
# check left if no no. found on right
if matched and get_insurer_num(text[:matched.span()[0]]):
return ret, text[:matched.span()[0]]
return ret, text
def kohi_num_match(text: str) -> Tuple[bool, Union[str, None]]:
"""Checks if 公費受給者番号 exists in text.
Args:
text: Text to check
Returns:
`(success, text)`, where `sucess` is `True` if matched, `False` if not,
and `text` is text truncated from the matched pattern if matched, `None`
if not.
e.g.
>>> insurer_match("123456受給者番号87654321")
True 受給者番号87654321
"""
ret, matched = match_one(KOHI_NUM, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def valid_from_match(text: str) -> Tuple[bool, Union[str, None]]:
"""Checks if 有効開始日 exists in text.
Args:
text: Text to check
Returns:
`(success, text)`, where `sucess` is `True` if matched, `False` if not,
and `text` is text truncated base on the matched pattern if matched,
`None` if not.
e.g.
>>> insurer_match("2021年12月12日有効開始日2021年1月1日")
True 有効開始日2021年1月1日
"""
for keyword in ["まで", "迄"]:
if keyword in text and len(get_date(text)) == 1:
return False, text
if re.search("自(?!己)", text):
return 2, text[text.index("自") + 1:]
match = re.search(r"か.$", text)
if match:
return 2, text[:match.span()[0]]
if "から" in text:
return 2, text[:text.index("から")]
if len(text) > 2 and text[-2] == "か":
return 2, text[:text.index("か")]
if text.endswith("日か"):
return 2, text[:-2]
ret, matched = match_one(VALID_FROM, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def valid_until_match(text: str) -> Tuple[bool, Union[str, None]]:
"""Checks if 有効終了日 exists in text.
Args:
text: Text to check
Returns:
`(success, text)`, where `sucess` is `True` if matched, `False` if not,
and `text` is text truncated base on the matched pattern if matched,
`None` if not.
e.g.
>>> insurer_match("有効開始日2021年12月12日有効終了日2021年1月1日")
True 有効終了日2021年1月1日
"""
text = UNTIL_FIX.sub(r"\g<1>有効", text)
if not PERCENT.search(text):
if "至" in text:
return 2, text[text.index("至") + 1:]
if "まで" in text and "までは" not in text and not PERCENT.search(text):
return 2, text[:text.index("まで")]
if "迄有効" in text and not PERCENT.search(text):
return 2, text[:text.index("迄有効")]
ret, matched = match_one(VALID_UNTIL, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def kofu_match(text: str) -> Tuple[bool, Union[str, None]]:
"""Checks if 交付年月日 exists in text.
Args:
text: Text to check
Returns:
`(success, text)`, where `sucess` is `True` if matched, `False` if not,
and `text` is text truncated until the matched pattern if matched, `None`
if not.
e.g.
>>> insurer_match("2009年12月1日交付有効終了日2021年1月1日")
True 2009年12月1日
"""
text = KOFU_FIX.sub("交付", text)
ret, matched = match_one(KOFU, text)
# nothing matched
if matched is None: return ret, text
# check right side first
if get_date(text[matched.span()[0]:]):
return ret, text[matched.span()[0]:]
# check left side if nothing on right
if get_date(text[:matched.span()[0]]):
return ret, text[:matched.span()[0]]
return ret, text
def skkget_match(text: str) -> Tuple[bool, Union[str, None]]:
"""Checks if 資格取得日 exists in text.
Args:
text: Text to check
Returns:
`(success, text)`, where `sucess` is `True` if matched, `False` if not,
and `text` is text truncated until the matched pattern if matched, `None`
if not.
e.g.
>>> insurer_match("2009年12月1日資格取得日2021年1月1日")
True 2021年1月1日
"""
if "認定日" in text:
return True, text[text.index("認定日") + 1:]
ret, matched = match_one(SKKGET, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def branch_match(text: str) -> Tuple[bool, Union[str, None]]:
"""Checks if 枝番 exists in text.
Args:
text: Text to check
Returns:
`(success, text)`, where `sucess` is `True` if matched, `False` if not,
and `text` is text truncated until the matched pattern if matched, `None`
if not.
e.g.
>>> insurer_match("12345枝番6789")
True 枝番6789
"""
ret, matched = match_one(BRANCH, text)
text = text if matched is None else text[matched.span()[0]:]
text = re.sub(r"番号\d+", "", text)
return ret, text
def score(
match_func: Callable[[str], Tuple[bool, str]],
texts: List[list],
no_ext: bool = False
) -> Tuple[np.ndarray, List[str]]:
"""Score each text line based on a given match function.
When `no_ext` is `True`, a matched line has a score of 2. The line above
it and the line below it has a score of 1.
When `no_ext` is `False`, a matched line has a score of 1, and each other
line has a score of 0.
Args:
match_func: A function used for pattern matching
texts: A list of textline information. Each element is also a list whose
last element is all text of thel textline.
no_ext: If give lines below/above the matched one positive scores.
Returns:
`(scores, texts)`, where `scores` is a `np.ndarray` whose length is the same
as texts. `texts` is all texts or `None` returned by `match_func` .
"""
match_results = [match_func(line[-1]) for line in texts]
scores = np.array([int(r[0]) for r in match_results])
cut_texts = [r[1] for r in match_results]
if no_ext:
return scores, cut_texts
scores_ext = scores.copy()
# 2 for the hit lines
scores_ext *= 2
# 1 for lines above/below the hit lines
scores_ext[:-1] += scores[1:]
scores_ext[1:] += scores[:-1]
return scores_ext, cut_texts
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,734
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/serve_cam.py
|
import yaml
from camera import CamServer
with open("config/camera.yaml", encoding="utf-8") as f:
conf = yaml.safe_load(f)
server = CamServer(conf)
server.start_pub()
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,735
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/finders/date.py
|
from copy import deepcopy
import yaml
import numpy as np
from .. import match
from .. import extract
from ..match import score
class DatesFinder(yaml.YAMLObject):
yaml_tag = u'!DatesFinder'
def __init__(self, match_methods, extract_method):
self.match_methods = match_methods
self.extract_method = extract_method
self.scores = {}
self.texts = {}
self.info = {}
def _score(self, texts):
for tag, match_func in self.match_methods.items():
self.scores[tag], self.texts[tag] = score(getattr(match, match_func), texts, no_ext=(tag != "Birthday"))
def extract(self, texts):
self.texts = {}
self.info = {}
self._score(texts)
# date match NMS
for i in range(len(texts)):
key_keep, suppress = None, False
for key, score in self.scores.items():
if score[i] < 2:
continue
if suppress:
# more than 1 line with score > 1
suppress = False
break
key_keep = key
suppress = True
if suppress:
for key in self.scores:
# do not suppress another single match
if key != key_keep and sum(self.scores[key]) - self.scores[key][i] > 0:
self.scores[key][i] = 0
# extract dates from lines with positive score for any key
extract_f = getattr(extract, self.extract_method)
dates_all = {}
for (tag, lines), (_, scores) in zip(self.texts.items(), self.scores.items()):
dates_all[tag] = [extract_f(line) if score > 0 else [] for score, line in zip(scores, lines)]
# handle 2 dates in the same line
for tag in ["YukoStYmd", "YukoEdYmd"]:
for dates in dates_all[tag]:
if len(dates) == 2:
self.info["YukoStYmd"], self.info["YukoEdYmd"] = dates
# assign dates recursively
for th in np.arange(np.max(list(self.scores.values())), 0, -1):
scores_prev = {}
while not all([np.all(scores_prev.get(k, None) == v) for k, v in self.scores.items()]):
scores_prev = deepcopy(self.scores)
for key in self.scores:
if self.info.get(key, None) is not None: continue
val_max, idx_max = self.scores[key].max(), self.scores[key].argmax()
if val_max >= th and len(self.scores[key][self.scores[key] == val_max]) == 1 \
and len(dates_all[key][idx_max]) == 1:
self.info[key] = dates_all[key][idx_max][0]
# clear other scores
for other_key in set(self.scores.keys()) - set(key):
self.scores[other_key][idx_max] = 0
# handle yukostymd and yukoedymd in the same line
if "YukoStYmd" not in self.info and "YukoEdYmd" not in self.info:
idx_from = self.scores["YukoStYmd"].argmax()
idx_until = self.scores["YukoEdYmd"].argmax()
dates_from = dates_all["YukoStYmd"][idx_from]
dates_until = dates_all["YukoEdYmd"][idx_until]
if str(dates_from) == str(dates_until) and len(dates_from) == 2:
self.info["YukoStYmd"], self.info["YukoEdYmd"] = dates_from
for key in self.scores:
if key not in self.info:
for idx in reversed(self.scores[key].argsort()):
if dates_all[key][idx]:
self.info[key] = dates_all[key][idx].pop(0)
break
for tag in self.match_methods:
if tag not in self.info:
self.info[tag] = None
return self.info
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,736
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ws_calib.py
|
import time
import json
import asyncio
import subprocess
import websockets
STEP = 10
def set_light(brightness):
cmd = ["/home/almexusr/client_test/set_light.sh", str(brightness)]
subprocess.run(cmd)
time.sleep(1)
async def ocr():
async with websockets.connect("ws://localhost:8766") as websocket:
await websocket.send('{"Scan": "Brightness"}')
res = await websocket.recv()
res = json.loads(res)
assert "Brightness" in res
brightness = int(res["Brightness"]) + STEP
set_light(res["Brightness"])
while res.get("Result", "NG") == "NG":
brightness -= STEP
set_light(brightness)
print("try", brightness)
await websocket.send('{"Scan": "MyNumTest"}')
res = await websocket.recv()
res = json.loads(res)
print("chose brightness", brightness)
with open("/home/almexusr/brightness.ini", "w") as f:
f.write(str(brightness))
while True:
if input("Put a MyNumber card, enter to continue, q to abort") == "q":
break
time.sleep(1)
await websocket.send('{"Scan":"MyNumber"}')
res = await websocket.recv()
res = json.loads(res)
await websocket.send('{"Patient":{"Birthday":{}},"MyNumber":{"YukoEdYmd":{},"Code":{}}}')
res = await websocket.recv()
res = json.loads(res)
for k, v in res.items():
if isinstance(v, dict):
for kk, vv in v.items():
if "text" in vv:
print(kk, vv["text"])
else:
print(kk, vv)
else:
print(k, v)
asyncio.get_event_loop().run_until_complete(ocr())
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,737
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/date.py
|
from info_extractor.re_pattern import LAST_DAY
ERA_OFFSET = {
"m": 1867,
"t": 1911,
"s": 1925,
"h": 1988,
"r": 2018,
"w": 0,
}
MONTH_LAST_DAY = {
'01':'31',
'02':'28',
'03':'31',
'04':'30',
'05':'31',
'06':'30',
'07':'31',
'08':'31',
'09':'30',
'10':'31',
'11':'30',
'12':'31',
}
class Date:
def __init__(self, year, month, date, era):
self.m = month
self.d = date
self.y = str(int(year) + ERA_OFFSET[era])
self.jpy = year if era != "w" else None
self.check_last_day()
def western_str(self):
date_str = self.y + self.m.zfill(2) + self.d.zfill(2)
return date_str
def mynum_str(self):
""" Generate string for MyNumber Car verification
"""
if self.jpy is None:
date_str = self.y[-2:] + self.m.zfill(2) + self.d.zfill(2)
else:
date_str = self.jpy.zfill(2) + self.m.zfill(2) + self.d.zfill(2)
return date_str
def __repr__(self):
return self.western_str()
def __str__(self):
return self.western_str()
def check_last_day(self):
if str(self.d) == '99':
if str(self.m.zfill(2)) == '02' and int(self.y)%4 ==0:
self.d=29
else:
self.d = MONTH_LAST_DAY[str(self.m.zfill(2))]
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,738
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/simple_reader.py
|
import unicodedata
import pickle
import cv2
import regex as re
import numpy as np
from .base_reader import BaseReader
from apps.utils_v1.text import *
class SimpleReader(BaseReader):
def __init__(self, client, logger, conf):
super().__init__(client=client, logger=logger, conf=conf)
def ocr(self, img):
img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
self.info = {}
boxes, scores = self.find_texts(img)
recog_results = self.read_texts(boxes=boxes)
texts = self.group_textlines(recog_results)
for l in texts:
print(l[-1])
# Birthday
for l in texts:
if birthday_match(l[-1]):
dates = get_date(l[-1])
if dates:
self.info["Birthday"] = dates[0]
break
# HknjaNum
for l in texts:
if insurer_match(l[-1]):
num = get_insurer_no(l[-1].replace("年", "").replace("月", ""), [])
if num:
self.info["HknjaNum"] = num[0]
break
# Num
for l in texts:
if re.search(r"(受給者番号){e<2}", l[-1]):
num = re.search(r"\d{6,8}", l[-1].replace("年", "").replace("月", ""))
if num:
self.info["Num"] = num[0]
# Kigo
# NumK
# YukoStYmd
for l in texts:
if valid_from_match(l[-1]):
dates = get_date(l[-1])
if dates:
self.info["YukoStYmd"] = dates[0]
break
# YukoEdYmd
for l in texts:
if valid_until_match(l[-1]):
dates = get_date(l[-1])
if dates:
self.info["YukoEdYmd"] = dates[0]
break
# JgnGak
# HknjaName
# RouFtnKbn
print(self.info)
return "公費"
def extract_info(self, key: str):
"""
Borrowed from mainstream insurance reader
"""
if key == 'SyuKbn':
return "公費"
else:
result = {"text": self.info.get(key, None), "confidence": 1.0}
return result
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,739
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/finders/simple.py
|
"""A naive key information finder"""
import yaml
from .. import match as m
from .. import extract as e
class SimpleFinder(yaml.YAMLObject):
yaml_tag = u'!SimpleFinder'
def __init__(self, match_method, extract_method):
self.match_method = match_method
self.extract_method = extract_method
def match_one(self, texts):
for line in texts:
mf = getattr(m, self.match_method)
ret, text = mf(line[-1])
if ret:
return text
def extract(self, texts):
text = self.match_one(texts)
if text is not None:
res = getattr(e, self.extract_method)(text)
return res
# class SimpleFinder(yaml.YAMLObject):
# """A naive key information finder.
# It matches a pattern in each given line, and extracts information from the
# exact line where the pattern is successfully matched.
# YAMLObject: This class can be saved as a YAML file for reuse.
# Typical usage example:
# >>> finder = SimpleFinder(
# match_method="birthday_match",
# extract_method="get_date"
# )
# >>> print(finder.extract([["生年月日1960年12月12日"], ["another line"]]))
# [19601212]
# Args:
# match_method: Name of the function for pattern matching, which has to be
# defined in `..match`
# extract_method: Name of the function for information extraction, which has
# to be defined in `..extract`
# """
# yaml_tag = u'!SimpleFinder'
# def __init__(self, match_method: str, extract_method: str):
# self.mf = getattr(m, match_method)
# self.ef = getattr(e, extract_method)
# def match_one(self, texts):
# for line in texts:
# ret, text = self.mf(line[-1])
# if ret:
# return text
# return None
# def extract(self, texts):
# text = self.match_one(texts)
# if text is not None:
# res = self.ef(text)
# return res
# return None
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,740
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/models/ctpnp_base.py
|
import numpy as np
from .utils.image import resize_ar, nms, get_rect
class CTPNPBase:
"""
CTPN-Pixel Base Class
"""
def __init__(self, logger, **kwargs):
self.logger = logger
self.min_score = kwargs.get('min_score', 0.2)
self.stride = kwargs.get('stride', 4)
self.iou_th = kwargs.get('iou_th', 0.5)
self.min_h = kwargs.get('min_h', 16)
self.max_hgap = kwargs.get('max_hgap', 32)
self.min_voverlap = kwargs.get('min_voverlap', 0.7)
self.min_size_sim = kwargs.get('min_size_sim', 0.7)
self.ratio = None
self.ori_shape = None
def preprocess(self, img: np.ndarray, nchw: bool = True):
self.ori_shape = img.shape
resized, self.ratio = resize_ar(img, self.input_w, self.input_h)
resized = resized.astype(np.float32) / 127.5 - 1
feed = resized.transpose(2, 0, 1) if nchw else resized
feed = feed[np.newaxis, ...]
return feed
def parse_result(self, cls_pred: np.ndarray, cnt_pred: np.ndarray, box_pred: np.ndarray, suppress_lines: bool = True):
scores = cnt_pred * cls_pred
yy, xx = np.where(scores[0, ..., 0] > self.min_score)
top_bot = box_pred[scores[..., 0] > self.min_score]
scores = scores[scores > self.min_score]
if scores.size == 0:
return np.array([]), np.array([])
real_x1 = xx * self.stride
real_x2 = real_x1 + self.stride
real_yc = yy * self.stride + self.stride / 2
real_y1 = real_yc - top_bot[:, 0]
real_y2 = real_yc + top_bot[:, 1]
real_boxes = np.concatenate([
real_x1[:, np.newaxis],
real_y1[:, np.newaxis],
real_x2[:, np.newaxis],
real_y2[:, np.newaxis]
], axis=1)
hs = real_boxes[:, 3] - real_boxes[:, 1]
real_boxes = real_boxes[hs > self.min_h]
scores = scores[hs > self.min_h]
final_boxes, final_scores = nms(real_boxes, scores, self.iou_th)
final_boxes /= self.ratio
lines = self._graph_connect(final_boxes, final_scores, tuple(self.ori_shape[:2]))
if suppress_lines:
lines = self.suppress_lines(lines)
return lines, final_boxes
def suppress_lines(self, lines: list):
suppressed = []
rects = get_rect(lines)
merged = []
for idx1, l1 in enumerate(lines):
skip = False
r1 = rects[idx1]
a1 = (r1[3] - r1[1]) * (r1[2] - r1[0])
for idx2, l2 in enumerate(lines):
if (l1 == l2).all():
continue
r2 = rects[idx2]
a2 = (r2[3] - r2[1]) * (r2[2] - r2[0])
if a2 < a1:
continue
inter_x0 = max(r1[0], r2[0])
inter_x1 = min(r1[2], r2[2])
inter_y0 = max(r1[1], r2[1])
inter_y1 = min(r1[3], r2[3])
inter_area = max(inter_x1 - inter_x0, 0) * max(inter_y1 - inter_y0, 0)
if inter_area / a1 > 0.5:
skip = True
continue
if (inter_y1 - inter_y0) / (max(r1[3], r2[3]) - min(r1[1], r2[1])) > 0.7 and r1[0] < r2[0] < r1[2] < r2[2]:
lines[idx1][2:6] = l2[2:6]
merged.append(idx2)
if not skip and idx1 not in merged:
suppressed.append(idx1)
suppressed = np.array([lines[idx] for idx in suppressed if idx not in merged])
return suppressed
def _check(self, h1: int, h2: int, box: np.ndarray, adj_box: np.ndarray):
# vertial IOU
u_y0 = min(box[1], adj_box[1])
u_y1 = max(box[3], adj_box[3])
i_y0 = max(box[1], adj_box[1])
i_y1 = min(box[3], adj_box[3])
v_iou = max(i_y1 - i_y0, 0) / (u_y1 - u_y0)
# size similarity
size_sim = min(h1, h2) / max(h1, h2)
valid = v_iou >= self.min_voverlap and size_sim >= self.min_size_sim
return valid
def _graph_connect(self, boxes: np.ndarray, scores: np.ndarray, size: tuple):
boxes[:, 0] = np.clip(boxes[:, 0], a_min=0, a_max=size[1] - 1)
boxes[:, 1] = np.clip(boxes[:, 1], a_min=0, a_max=size[0] - 1)
boxes[:, 2] = np.clip(boxes[:, 2], a_min=0, a_max=size[1] - 1)
boxes[:, 3] = np.clip(boxes[:, 3], a_min=0, a_max=size[0] - 1)
box_heights = boxes[:, 3] - boxes[:, 1]
x_groups = [[] for _ in range(size[1])]
for i, box in enumerate(boxes):
x_groups[int(box[0])].append(i)
graph = np.zeros((boxes.shape[0], boxes.shape[0]), np.bool)
for i, box in enumerate(boxes):
# look for successive boxes
succ_indices = []
start = max(int(box[0] + 1), 0)
end = min(int(box[0] + self.max_hgap + 1), size[1])
for x in range(start, end):
for adj_idx in x_groups[x]:
if self._check(box_heights[i], box_heights[adj_idx], box, boxes[adj_idx]):
succ_indices.append(adj_idx)
if len(succ_indices) != 0:
break
if len(succ_indices) == 0:
continue
# get index of successive box with highest score
succ_idx = succ_indices[np.argmax(scores[succ_indices])]
succ_box = boxes[succ_idx]
# look for precursive boxes
prec_indices = []
start = max(int(succ_box[0] - 1), 0)
end = max(int(succ_box[0] - 1 - self.max_hgap), 0)
for x in range(start, end, -1):
for adj_idx in x_groups[x]:
if self._check(box_heights[succ_idx], box_heights[adj_idx], succ_box, boxes[adj_idx]):
prec_indices.append(adj_idx)
if len(prec_indices) > 0:
break
if not prec_indices:
continue
if scores[i] >= np.max(scores[prec_indices]):
graph[i, succ_idx] = True
# group text lines
line_groups = []
for i in range(graph.shape[0]):
if not graph[:, i].any() and graph[i, :].any():
line_groups.append([i])
v = i
while graph[v, :].any():
v = np.where(graph[v, :])[0][0]
line_groups[-1].append(v)
text_lines = np.zeros((len(line_groups), 9), np.float32)
for line_idx, box_indices in enumerate(line_groups):
line_boxes = boxes[box_indices]
if line_boxes.shape[0] == 1:
x0, x1 = line_boxes[0, 0], line_boxes[0, 2]
top_y0, top_y1 = line_boxes[0, 1], line_boxes[0, 1]
bot_y0, bot_y1 = line_boxes[0, 3], line_boxes[0, 3]
else:
x0 = np.min(line_boxes[:, 0])
x1 = np.max(line_boxes[:, 2])
top = np.poly1d(np.polyfit(line_boxes[:, 0], line_boxes[:, 1], 1))
bot = np.poly1d(np.polyfit(line_boxes[:, 2], line_boxes[:, 3], 1))
top_y0, top_y1 = top(x0), top(x1)
bot_y0, bot_y1 = bot(x0), bot(x1)
score = np.mean(scores[list(box_indices)])
text_lines[line_idx] = np.array([x0, top_y0, x1, top_y1, x1, bot_y1, x0, bot_y0, score])
return text_lines
def infer_sync(self, img: np.ndarray, suppress_lines: bool = True, x_mask: float = 1e9, y_mask: float = 0):
raise NotImplementedError
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,741
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/match.py
|
import numpy as np
import regex as re
from .extract import get_date
from .re_pattern import BIRTHDAY, INSURER, KOHI_NUM, VALID_FROM, UNTIL_FIX, VALID_UNTIL, KOFU_FIX, KOFU, SKKGET, PERCENT
def match_one(patterns: list, text: str):
for p in patterns:
matched = p.search(text)
if matched is not None:
return True, matched
return False, None
def birthday_match(text: str):
if BIRTHDAY.search(text):
return True, text
return False, text
def insurer_match(text: str):
ret, matched = match_one(INSURER, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def kohi_num_match(text: str):
ret, matched = match_one(KOHI_NUM, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def valid_from_match(text: str):
for keyword in ["まで", "迄"]:
if keyword in text and len(get_date(text)) == 1:
return False, text
if re.search("自(?!己)", text):
return 2, text[text.index("自") + 1:]
match = re.search(r"か.$", text)
if match:
return 2, text[:match.span()[0]]
if "から" in text:
return 2, text[:text.index("から" )]
if len(text) > 2 and "か" == text[-2]:
return 2, text[:text.index("か")]
if text.endswith("日か"):
return 2, text[:-2]
ret, matched = match_one(VALID_FROM, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def valid_until_match(text: str):
text = UNTIL_FIX.sub(r"\g<1>有効", text)
if not PERCENT.search(text):
if "至" in text:
return 2, text[text.index("至") + 1:]
for key in ["まで", "迄有効"]:
if key in text and not PERCENT.search(text):
return 2, text[:text.index(key)]
ret, matched = match_one(VALID_UNTIL, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def kofu_match(text: str):
text = KOFU_FIX.sub("交付", text)
ret, matched = match_one(KOFU, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def skkget_match(text: str):
if "認定日" in text:
return True, text[text.index("認定日") + 1:]
ret, matched = match_one(SKKGET, text)
text = text if matched is None else text[matched.span()[0]:]
return ret, text
def score(match_func, texts, no_ext=False):
match_results = [match_func(line[-1]) for line in texts]
scores = np.array([int(r[0]) for r in match_results])
cut_texts = [r[1] for r in match_results]
if no_ext:
return scores, cut_texts
scores_ext = scores.copy()
# 2 for the hit lines
scores_ext *= 2
# 1 for lines above/below the hit lines
scores_ext[:-1] += scores[1:]
scores_ext[1:] += scores[:-1]
return scores_ext, cut_texts
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,742
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/models/dense8_base.py
|
import numpy as np
import cv2
from .utils.general import softmax, greedy_decode
from .utils.image import resize_h
class Dense8Base:
"""
DenseNet8 Inference Class
"""
def __init__(self, logger, **kwargs):
self.logger = logger
self.input_len = None
self.ratio = None
def preprocess(self, img, nchw=True):
self.ratio = self.input_h / img.shape[0]
img_pad, img_resize = resize_h(img, h=self.input_h, w=self.input_w, logger=self.logger)
if nchw:
img_pad = img_pad.transpose(2, 0, 1)
img_pad = img_pad[np.newaxis, ...].astype(np.float32)
self.input_len = img_resize.shape[1] // (self.input_h // 4)
return img_pad
def parse_result(self, logits, num_only):
logits = logits.reshape(logits.shape[1], logits.shape[-1])
if len(logits.shape) == 4:
logits = logits.transpose(1, 0)
if num_only:
logits_num = np.zeros_like(logits)
num_indices = [1,6,17,31,34,42,46,49,50,39, logits.shape[-1]-1]
logits_num[:, num_indices] = logits[:, num_indices]
#probs = softmax(logits_num)
probs = logits_num
else:
#probs = softmax(logits)
probs = logits
codes, probs, positions = greedy_decode(probs, self.input_len)
positions = (positions * (self.input_h // 4) + (self.input_h // 8)) / self.ratio
return codes, probs, positions
def infer_sync(self, img, num_only=False):
raise NotImplementedError
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,743
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/__init__.py
|
"""Analyzers that extract key information from OCR results for different kinds
of insurances"""
from .main_analyzer import MainAnalyzer
from .kouhi_analyzer import KouhiAnalyzer
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,744
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/phrase_locator.py
|
import unicodedata
import pickle
import cv2
import regex as re
import numpy as np
from .base_reader import BaseReader
class PhraseLocator(BaseReader):
def find(self, img, phrases):
boxes, scores = self.find_texts(img)
recog_results = self.read_texts(boxes=boxes)
texts = self.group_textlines(recog_results)
results = {}
for line in texts:
print(line[-1])
for tag, text in phrases.items():
if tag in results: continue
pattern = re.compile("\D?".join([c for c in text]))
matched = pattern.search(line[-1])
if matched or (tag == "yuko_ed_ymd" and line[-1].endswith("で")):
text = None
if matched:
text = matched.group(0)
else:
text = line[-1]
start = line[-1].index(text)
end = start + len(text) - 1
lengths = [0] * (len(line) - 1)
lengths[0] = len(line[0][0])
box_start = None
box_end = None
print(line[-1], text)
for i in range(len(lengths)):
if i > 0: lengths[i] = lengths[i - 1] + len(line[i][0])
print(line[i][0], lengths[i], start, end)
if lengths[i] >= start and box_start is None:
box_start = line[i][3]
if lengths[i] >= end and box_end is None:
box_end = line[i][3]
break
x1 = box_start[0]
x2 = box_end[2]
y1 = min(box_start[1], box_end[1])
y2 = max(box_start[3], box_end[3])
merged_box = np.array([x1, y1, x2, y2])
results[tag] = merged_box
return results
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,745
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/utils/image.py
|
def crop(img):
crop = img.copy()
#crop = crop[300:-300, 200:-200, :]
crop = crop[535:1445, 600:2150, :]
return crop
def crop_print(img):
return img[470:1435, 600:2130]
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,746
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/utils/type_check.py
|
"""Helper functions for type checks."""
from typing import Any
def assure_type(var: Any, var_type: Any):
"""Check variable type
Args:
var: a variable
var_type: exectped type of the variable
Raises:
TypeError: `var` is not an instance of `var_type`
"""
if not isinstance(var, var_type):
raise TypeError(f"Expected {var_type}, got {type(var)}")
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,747
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/client_mock.py
|
import time
import yaml
from .models import DBNetArmNN, Dense8ArmNN
from .utils import ArmNNRuntime
class ModelClientMock:
def __init__(self, logger):
with open('config/model_server_config.yaml', encoding='utf-8') as f:
self.config = yaml.safe_load(f)
with open('config/err.yaml', encoding='utf-8') as f:
self.err = yaml.safe_load(f)
self.logger = logger
common_setting = {"logger": logger, "runtime": ArmNNRuntime()}
self.dbnet = {
'landscape': DBNetArmNN(
**self.config['dbnet']['armnn']['landscape'],
**common_setting,
),
'portrait': DBNetArmNN(
**self.config['dbnet']['armnn']['portrait'],
**common_setting,
)
}
self.dense = {}
dense_config = self.config['dense8']['armnn']
backend = dense_config['backend']
for path in dense_config["model_path"]:
model = Dense8ArmNN(path, backend=backend, **common_setting)
self.dense[int(model.input_w)] = model
self.height = model.input_h
def infer_sync(self, sess_id, network, img, key=None, num_only=None, layout=None, suppress_lines=None):
if network == 'DBNet':
t0 = time.time()
boxes, scores, angle = self.dbnet[layout].infer_sync(img)
self.logger.debug(f'DBnet total: {time.time() - t0:.3f}s')
return boxes, scores, angle
elif network == 'Dense':
codes, probs, positions = self.dense[key].infer_sync(img, num_only=num_only)
return codes, probs, positions
else:
raise ValueError(f"{network} is not implemented")
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,748
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/apps/insurance_reader.py
|
"""App that extracts information from insurance card image
"""
from pathlib import Path
import pickle
import logging
from typing import Any
import cv2
import numpy as np
from ..utils.image import get_rect, get_chips, rotate_if_necessary, merge, rotate
from ..utils.general import group_lines
from ..utils.text import fuzzy_match, clean_half_width
INSURANCE_WORDS = [
'保険',
'共済',
'受給',
'公費',
'高齢',
'限度額',
'資格取得',
'番号',
'記号',
]
KOUHI_WORDS = [
'公費',
'ひとり親',
'子育て支援',
'指定難病',
'心身障害者医療',
]
GENDO_WORDS = [
'限度額認証',
'限度額適用'
]
KOUREI_WORDS = [
'高齢',
'髙齢',
'高齡',
'髙齡',
]
class InsuranceReader:
"""OCR-based reader for insurance card.
This is the class one uses to extract information in key-value pairs from
insurance card images. It integrates modules that acutcally do OCR and
key information extraction, thus requires corresponding instances during
instantiation. All information has already been extracted when ocr_sync
if done, and extract_info simply serves as an API that can be used by
other packages.
Typical usage example:
>>> reader = InsuranceReader(
>>> model_server = a_client_of_model_server,
>>> analyzers = {"a": analyzer_for_a, "b": analyzer_for_b},
>>> logger = python_logger
>>> )
>>> syukbn = reader.ocr_sync(sess_id="123", img=img)
>>> print(syukbn)
主保険
>>> hknja_num = reader.extract_info("HknjaNum")
>>> print(hknja_num)
12345678
>>> bdate = reader.extract_info("Birthday")
>>> print(bdate)
20210401
Args:
model_server: An instance of `model_serving.client.Client`
analyzers: A dict of analyzers to extract infomation
from OCR results. Keys are possible values of syukbn that can be
returned by ocr_sync. Information extraction will be skipped if
there is no corresponding analyzer for a syukbn.
logger: A logging.Logger
"""
def __init__(self,
model_server: Any,
analyzers: dict,
logger: logging.Logger):
self.model_server = model_server
self.logger = logger
self.root_folder = Path(__file__).resolve().parent.parent
with open(str(self.root_folder / 'id2char_std.pkl'), 'rb') as f:
self.id2char = pickle.load(f)
# standard charset
assert len(self.id2char) == 7549
self.is_portrait = False
self.img = None
self.info = {}
self.syukbn = 'Uknown'
self.session_id = 'init_id'
self.min_wh_ratio = 0.5
self.analyzers = analyzers
self.pth = 0.5
def prefetch_hknjanum(self):
"""Extracts 保険者番号"""
hknjanum = self.analyzers["主保険"].finders["HknjaNum"].extract(self.texts)
if hknjanum is None: hknjanum = ""
return hknjanum
def read_page_sync(self, img: np.ndarray, layout: str = None) -> list:
"""Reads text from an image and group results in textlines.
Args:
img: Image to run OCR on
layout: Layout (portrait/landscape) based on which a text detection
model is chosen
Returns:
OCR results in a list. Each element contains bounding box and recognized
text for a line.
"""
recog_results = []
# check layout
if img.shape[0] > img.shape[1]:
self.is_portrait = True
layout = 'portrait'
else:
self.is_portrait = False
layout = 'landscape'
# detect text
det_res = self.model_server.infer_sync(
sess_id=self.sess_id, network='Det',
img=img,
layout=layout,
suppress_lines=False,
check_local=False
)
if 'lines' in det_res:
lines = det_res['lines']
else:
return det_res
# abort if less than 2 text boxes are detected
if lines.shape[0] < 2:
self.logger.info(f'{lines.shape[0]} text boxes detected')
return np.array([]), recog_results
# filter out invalid boxes
lines[lines < 0] = 0
self.logger.debug(f'Detected text boxes b4 wh ratio filter: {len(lines)}')
text_boxes = get_rect(lines, min_wh_ratio=self.min_wh_ratio)
text_boxes = merge(text_boxes)
self.logger.debug(f'Detected text boxes after wh ratio filter: '
f'{len(text_boxes)}, min wh ratio: {self.min_wh_ratio}')
# abort if less than 2 text boxes are detected
text_boxes = np.array(text_boxes)
if text_boxes.shape[0] < 2:
self.logger.info(f'{lines.shape[0]} text boxes detected')
return np.array([]), recog_results
# rotate when the detected angle is larger than 0.1 degree
if 'angle' in det_res and np.abs(det_res['angle']) > 0.1:
img = rotate(img, det_res["angle"])
self.img = img
# text recognition
chips = get_chips(img, text_boxes)
recog_res_dict = self.model_server.infer_batch_sync(
sess_id=self.sess_id,
network='Dense',
imgs=chips,
num_onlys=[False]*len(chips),
check_local=False
)
if 'codes' not in recog_res_dict: return recog_res_dict
for idx, (box, codes) in enumerate(zip(
text_boxes,
recog_res_dict["codes"]
)):
probs, positions = (
recog_res_dict["probs"][idx],
recog_res_dict["positions"][idx],
)
if codes.size == 0:
continue
indices = probs > self.pth
probs = probs[indices]
positions = positions[indices]
codes = codes[indices]
text = "".join([self.id2char[c] for c in codes])
if text:
recog_results.append([text, probs, positions, box])
# group text areas in lines
texts = group_lines(recog_results)
return texts
def is_kouhi(self, all_txt: str) -> bool:
"""Determines if an insurance is 公費.
Args:
all_txt: A single string containing all text recognized from an image.
Returns:
A boolean indicating if the image is a 公費
"""
# check keywords
if not self.is_portrait and ('兼高齢' in all_txt or '蒹高齢' in all_txt): return False
for w in KOUHI_WORDS:
if len(w) < 4 and w in all_txt: return True
if 4 <= len(w) <= 6 and fuzzy_match(w, all_txt): return True
if len(w) > 6 and fuzzy_match(w, all_txt, e_max=3): return True
# check insurer number
hknjanum = self.prefetch_hknjanum()
if hknjanum.startswith('81') or hknjanum.startswith('82'): return True
return False
def is_gendo(self, all_txt: str) -> bool:
"""Determines if an insurance is gendo.
Args:
all_txt: A single string containing all text recognized from an image.
Returns:
A boolean indicating if the image is a 限度額認定証
"""
for w in GENDO_WORDS:
if fuzzy_match(w, all_txt): return True
return False
def is_kourei(self, all_txt: str) -> bool:
"""Determines if an insurance is 高齢受給者証.
Args:
all_txt: A single string containing all text recognized from an image.
Returns:
A boolean indicating if the image is a 高齢受給者証
"""
if fuzzy_match('後期高齢者医療被保険者証', all_txt): return False
if not self.is_portrait and ('兼高齢' in all_txt or '蒹高齢' in all_txt): return False
if any([w in all_txt for w in KOUREI_WORDS]):
if (not self.is_portrait) and self.prefetch_hknjanum().startswith('39'):
return False
return True
return False
def validate(self, texts: list) -> bool:
"""Checks if text is from an insurance.
Args:
texts: Return value of read_page_sync, OCR results in a list.
Returns:
A boolean indicating if the image is an insruance.
"""
if not texts:
self.logger.warning('No text detected, categorized as Unknown')
return False
all_txt = ''.join([w[0] for line in texts for w in line if len(w) > 1])
if not sum([w in all_txt for w in INSURANCE_WORDS]) > 1:
self.logger.warning('No isnurance key word found, categorized as Unknown')
return False
return True
def categorize(self, texts: list) -> str:
"""Determines 主区分 of an image based on OCR results.
Args:
texts: Return value of read_page_sync, OCR results in a list.
Returns:
A string indicating 主区分
"""
all_txt = ''.join([line[-1] for line in texts])
if '介護' in all_txt:
self.logger.warning('kaigo detected, categorized as Unknown')
return 'Unknown'
if self.is_kouhi(all_txt):
return '公費'
if self.is_gendo(all_txt):
return '限度額認証'
if self.is_kourei(all_txt):
return '高齢受給者'
return '主保険'
def ocr_sync(self, sess_id: str, img: np.ndarray) -> str:
"""Runs OCR on insurance card.
Args:
sess_id: Session ID used in communication with the model server
img: Image to extract information from
Returns:
A string indicating Syukbn of the input image.
"""
self.info = {}
for tag in self.analyzers:
self.analyzers[tag].info.clear()
self.sess_id = sess_id
img = rotate_if_necessary(img, 1600, self.logger)
# correct the orientation
rotations = [
None,
cv2.ROTATE_180,
cv2.ROTATE_90_CLOCKWISE,
cv2.ROTATE_180,
]
for rot in rotations:
if rot is not None: img = cv2.rotate(img, rot)
results = self.read_page_sync(img)
# handle error
if isinstance(results, dict): return results
# check if a valid insurance based OCR results
valid = self.validate(results)
if valid: break
# abort if not a valid insurance
if not valid:
self.syukbn = 'Unknown'
self.img = img
return self.syukbn
# clean nums and convert to half width
texts = clean_half_width(results)
self.texts = texts
for line in texts:
print(" ".join(w[0] for w in line[:-1]))
print(line[-1])
# categorize insurance
syukbn = self.categorize(texts)
self.syukbn = syukbn
# extract info
if syukbn not in self.analyzers: return syukbn
self.analyzers[syukbn].fit(texts)
self.info = self.analyzers[syukbn].info
return syukbn
def extract_info(self, key: str) -> str:
"""Gets information for a specific item.
Args:
key: Name of the item to extract.
Returns:
A string for the item if it is sucessfully extracted, `None` otherwise.
For example:
>>> reader.extract_info("HknjaNum")
12345678
>>> reader.extract_info("Birthday")
20210401
"""
res = self.info.get(key, None)
if res is not None and not isinstance(res, str): res = str(res)
return res
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,749
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/finders/wide.py
|
"""A finder that extracts information from lines near a matched pattern"""
import yaml
import numpy as np
from .. import match as m
from ..match import score
from .. import extract as e
class WideFinder(yaml.YAMLObject):
"""A finder that extracts information from lines near matched patterns.
It matches a pattern in each given line, and tries to extract information
from the line where the pattern is sucessfully matched. If nothing can be
extracted, it will try the line above and the line below.
YAMLObject: This class can be saved as a YAML file for reuse.
Typical usage example:
>>> finder = WideFinder(
match_method="birthday_match",
extract_method="get_date"
)
>>> print(finder.extract([["生年月日1960年12月12日"], ["another line"]]))
[19601212]
>>> print(finder.extract([["生年月日"], ["1960年12月12日"]]))
[19601212]
Args:
match_method: Name of the function for pattern matching, which has to be
defined in `..match`
extract_method: Name of the function for information extraction, which has
to be defined in `..extract`
"""
yaml_tag = u'!WideFinder'
def __init__(self, match_method: str, extract_method: str):
self.mf = getattr(m, match_method)
self.ef = getattr(e, extract_method)
self.scores = np.array([])
self.texts = []
def extract(self, texts):
self.scores, self.texts = score(self.mf, texts)
print(self.scores,self.mf)
for idx in (-self.scores).argsort(kind="meregesort"):
if self.scores[idx] == 0: break
res = self.ef(self.texts[idx])
if res: return res
return None
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,750
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/base_reader.py
|
import time
import pickle
import unicodedata
from pathlib import Path
import numpy as np
import cv2
from .utils.image import merge, group_lines, get_clahe, draw_boxes, save_chips
class BaseReader:
def __init__(self, client, logger, conf):
self.client = client
self.logger = logger
preproc_conf = conf.get("preprocess", {})
self.det_preproc = preproc_conf.get("detection", None)
self.recog_preproc = preproc_conf.get("recognition", None)
with open(str('./id2char_std.pkl'), 'rb') as f:
self.id2char = pickle.load(f)
assert len(self.id2char) == 7549
self.clahe_op = get_clahe(conf["preprocess"]["clahe"])
self.info = {}
self.img = None
self.det_img = None
self.debug = conf.get("debug", {})
if isinstance(self.debug.get("output", None), str):
self.debug_out = Path(self.debug["output"])
self.debug_out.mkdir(exist_ok=True)
def clahe(self, img):
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
img_clahe = self.clahe_op.apply(gray)
img_clahe = np.concatenate([img_clahe[..., np.newaxis]]*3, axis=-1)
self.det_img = img_clahe
return img_clahe
def get_key(self, chip, lengths, height):
lengths = sorted(lengths)
w = int(height / chip.shape[0] * chip.shape[1])
key = lengths[-1]
for l in lengths:
if w <= l:
key = l
break
return key
def find_texts(self, img):
self.img = img
self.det_img = None
t0 = time.time()
preproc = getattr(self, self.det_preproc)
t0 = time.time()
feed_img = preproc(img) if self.det_preproc is not None else img
layout = "portrait" if img.shape[0] > img.shape[1] else "landscape"
boxes, scores, angle = self.client.infer_sync(None, "DBNet", feed_img.copy(), layout=layout)
if np.abs(angle) > 0.1:
print("ANGLE", angle)
m = cv2.getRotationMatrix2D((img.shape[1]//2, img.shape[0]//2), angle, 1)
if self.img is not None: self.img = cv2.warpAffine(self.img, m, (img.shape[1], img.shape[0]), cv2.INTER_CUBIC)
if self.det_img is not None: self.det_img = cv2.warpAffine(self.det_img, m, (img.shape[1], img.shape[0]), cv2.INTER_CUBIC)
boxes = np.array(merge(boxes))
if self.debug["draw_boxes"]: draw_boxes(self.det_img, boxes, self.debug_out)
return boxes, scores
def read_single_line(self, chip, box, num_only):
lengths = list(self.client.dense.keys())
height = self.client.height
codes, probs, positions = self.client.infer_sync(None, 'Dense', chip, key=self.get_key(chip, lengths, height), num_only=num_only)
text = ''.join([self.id2char[c] for c in codes])
line = [[text, probs, positions, box], text]
return line
def read_texts(self, boxes):
img = self.det_img if self.recog_preproc == self.det_preproc and self.det_img is not None else self.img
boxes = boxes.astype(int)
chips = map(lambda b: img[b[1]:b[3], b[0]:b[2]], boxes)
chips = map(lambda img: cv2.resize(img, (int(64 / img.shape[0] * img.shape[1]), 64), cv2.INTER_AREA), chips)
chips = list(chips)
if self.debug["save_chips"]: save_chips(chips, self.debug_out)
results = []
while len(chips) > 0:
merged_chip = (np.ones((64, 704 * 2, 3)) * 128).astype(np.uint8)
start = 0
ranges = []
while len(chips) > 0 and 704 * 2 - start > chips[0].shape[1]:
chip = chips.pop(0)
merged_chip[:, start: start+chip.shape[1]] = chip
end = start + chip.shape[1]
ranges.append((start, end))
start = end + 64
if len(ranges) == 0:
chip = chips.pop(0)
merged_chip = chip
ranges.append((0, 704 * 2))
codes, probs, positions = self.client.infer_sync(None, 'Dense', merged_chip, key=704*2, num_only=False)
#cv2.imwrite(f"./debug/merged_{len(chips)}_left.jpg", merged_chip)
for r in ranges:
pick = np.logical_and(r[0] <= positions, positions <= r[1])
text = ''.join([self.id2char[c] for c in codes[pick]])
text = unicodedata.normalize('NFKC', text)
results.append((text, probs[pick], positions[pick]))
results_with_box = [[r[0], r[1], r[2], b] for r, b in zip(results, boxes)]
return results_with_box
def group_textlines(self, recog_results):
textlines = group_lines(recog_results)
return textlines
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,751
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/finders/simple.py
|
import yaml
from .. import match as m
from .. import extract as e
class SimpleFinder(yaml.YAMLObject):
yaml_tag = u'!SimpleFinder'
def __init__(self, match_method, extract_method):
self.match_method = match_method
self.extract_method = extract_method
def match_one(self, texts):
for line in texts:
mf = getattr(m, self.match_method)
ret, text = mf(line[-1])
if ret:
return text
def extract(self, texts):
text = self.match_one(texts)
if text is not None:
res = getattr(e, self.extract_method)(text)
return res
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,752
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/finders/rouftnkbn.py
|
"""A finder to extract 適用区分 and 負担割合 from OCR results"""
from typing import List, Any, Union
import yaml
from ..re_pattern import PERCENT_SINGLE_DIGIT, PERCENT, PERCENT_TAG, DIV_TAG, KBN, GEN
class RouFtnKbnFinder(yaml.YAMLObject):
"""A finder class to extract 負担区分 and 負担割合 from OCR results.
NOTE: 適用区分 and 負担割合 are considered as the same item for output.
Typical usage example:
>>> finder = RouFtnKbnFinder()
>>> res = finder.extract([["適用区分Ⅳ"]])
>>> print(res)
Ⅳ
"""
yaml_tag = u'!RouFtnKbnFinder'
def extract(self, texts: List[List[Any]]) -> Union[str, None]:
"""Extracts 負担区分 and 負担割合 from text lines.
Args:
texts: OCR results in a list, each element of each has also to be a
list, each element of which is the text for each detected line.
Returns:
A string of 負担区分 and 負担割合 if anything extracted, `None` otherwise.
"""
#pylint: disable=too-many-nested-blocks
self.info = {}
for idx_l, line in enumerate(texts):
single_num = PERCENT_SINGLE_DIGIT.findall(line[-1])
if single_num:
self.info['RouFtnKbn'] = single_num[0][1] + "割"
break
cat = PERCENT.findall(line[-1])
if cat:
self.info['RouFtnKbn'] = cat[0]
break
if PERCENT_TAG.search(line[-1]):
# num displacement
if line[-1].endswith('割'):
if idx_l > 0:
prev_line = texts[idx_l - 1][-1]
if prev_line.isdigit() and len(prev_line) == 1:
self.info['RouFtnKbn'] = prev_line + '割'
break
if idx_l < len(texts) - 1:
next_line = texts[idx_l + 1][-1]
if next_line.isdigit() and len(next_line) == 1:
self.info['RouFtnKbn'] = next_line + '割'
break
cap = DIV_TAG.findall(line[-1])
if cap:
convert1 = {
'i': 'Ⅰ',
'1': 'Ⅰ',
'l': 'Ⅰ',
'v': 'Ⅴ',
}
convert2 = {
'ii': 'Ⅱ',
'II': 'Ⅱ',
'iv': 'Ⅳ',
'1v': 'Ⅳ',
'lv': 'Ⅳ',
'vi': 'Ⅵ',
'v1': 'Ⅵ',
'vl': 'Ⅵ',
}
convert3 = {
'iii': 'Ⅲ',
'lll': 'Ⅲ',
'III': 'Ⅲ',
'II': 'Ⅱ',
'IV': 'Ⅳ',
'VI': 'Ⅵ',
'V': 'Ⅴ',
'I': 'Ⅰ',
'ァ': 'ア',
'ィ': 'イ',
'ゥ': 'ウ',
'ェ': 'エ',
'工': 'エ',
'ォ': 'オ',
}
if len(line[-1]) >= len(cap[0]) + 1:
kbn = line[-1][line[-1].index(cap[0]) + len(cap[0]):]
for cvt in [convert3, convert2, convert1]:
for k in cvt:
if k in kbn:
kbn = kbn.replace(k, cvt[k])
for key_word in 'アイウエオ':
if key_word in kbn:
kbn = key_word
break
self.info['RouFtnKbn'] = kbn
break
if idx_l > 0:
print(f'RouFtnKbn not found in the same line with tag, '
f'check the line above')
cat = KBN.findall(texts[idx_l - 1][-1])
if not cat:
cat = GEN.findall(texts[idx_l - 1][-1])
if cat:
kbn = cat[0]
for cvt in [convert3, convert2, convert1]:
for k in cvt:
if k in kbn:
kbn = kbn.replace(k, cvt[k])
for key_word in 'アイウエオ':
if key_word in kbn:
kbn = key_word
break
self.info['RouFtnKbn'] = kbn
break
if idx_l < len(texts) - 1:
print(f'RouFtnKbn not found in the same line with tag, '
f'check the line below')
cat = KBN.findall(texts[idx_l + 1][-1])
if not cat:
cat = GEN.findall(texts[idx_l + 1][-1])
if cat:
kbn = cat[0]
for cvt in [convert3, convert2, convert1]:
for k in cvt:
if k in kbn:
kbn = kbn.replace(k, cvt[k])
for key_word in 'アイウエオ':
if key_word in kbn:
kbn = key_word
break
self.info['RouFtnKbn'] = kbn
break
if "RouFtnKbn" not in self.info:
self.info["RouFtnKbn"] = None
return self.info["RouFtnKbn"]
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,753
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/utils/check.py
|
from pathlib import Path
def ensure_type(v, t, msg=""):
if not isinstance(v, t):
raise TypeError(msg)
def valid_path(p):
suffix = 0
while p.exists():
p = Path(str(p).replace(p.stem, p.stem + str(suffix)))
return p
def validate_json(msg):
if 'Scan' in msg or 'Patient' in msg or 'MyNumber' in msg:
return True
return False
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,754
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/extract.py
|
"""Functions to extract an named entity from text"""
from typing import Union, List, Any, Callable
import regex as re
from .re_pattern import DATE, LAST_DAY, INSURER_NUM, PURE_NUM
from .re_pattern import KIGO_NUM, KIGO_SINGLE, NUM_SINGLE
from .date import Date
def extract_one(patterns: list, text: str) -> Union[Any, None]:
"""Searches multiple patterns in text and returns the first match.
Args:
patterns: A list of compiled regex expression
text: Text to search patterns in
Returns:
Matched content if any, `None` otherwise
"""
for p in patterns:
# print(p)
res = p.findall(text)
if res is not None and res and res[0]:
res = res[0]
return res
return None
def clean_date(text: str) -> str:
"""Relaces special words in a date string.
Args:
text: Date string to clean
Returns:
A cleaned string.
"""
text = text.replace("元年", "1年")
text = LAST_DAY.sub("99日", text)
return text
def get_date(text: str) -> List[Date]:
"""Extracts all dates from text.
Args:
text: Text to extract dates from
Returns:
A list of all dates that can be extracted from the text. Each date is
a `Date` instance.
"""
text = clean_date(text)
dates = []
for era, pattern in DATE.items():
matches = pattern.findall(text)
if not matches: continue
for m in matches:
if m[0].isdigit():
dates.append(Date(year=m[0], month=m[2], date=m[4], era=era))
else:
dates.append(Date(year=m[1], month=m[3], date=m[5], era=era))
return dates
def get_one_date(text: str) -> Union[Date, None]:
"""Gets one date from text
This function calls `get_date` and returns the first element in
the returned list. Therefore the returned date depends on the
actual implementation of `get_date`, which means it does NOT
have to be the first date appears in the text.
Args:
text: Text to extract dates from
Returns:
An Date instance if any date can be extracted from the text,
`None` otherwise.
"""
dates = get_date(text)
if dates:
return dates[0]
return None
def date_western_str(text: str) -> List[str]:
"""Extracts dates as strings (western calendar year) from text.
Args:
text: Text to extract dates from
Returns:
A list of date strings. Empty if no date can be extracted.
"""
return [d.western_str() for d in get_date(text)]
def get_insurer_num(text: str) -> Union[str, None]:
"""Extracts insurer number from text.
Args:
text: Text to extract insurer number from
Returns:
A string of insurer number. None if nothing can be extracted.
"""
num = None
if len(text) < 3:
return num
for keyword in ["受給", "資格者"]:
if keyword in text:
text = text[:text.index(keyword)]
matches = INSURER_NUM.findall(text)
if matches:
num = matches[0]
elif re.search("電話\d",text):
return num
elif not re.search("\d{2,3}-\d{4}-\d{4}", text):
# get rid of wierd marks and try again
new_text = re.sub(r"[l\pP]+", "", text)
matches = INSURER_NUM.findall(new_text)
if matches: num = matches[0]
return num
def get_pure_num(text: str) -> Union[str, None]:
"""Extracts a pure number from text.
Args:
text: Text to extract a number from
Returns:
A number string. `None` if no number can be extracted.
"""
matched = PURE_NUM.search(text)
if matched is None:
return matched
return matched.group(0)
def get_kigo_num(text: str) -> Union[tuple, None]:
"""Extracts 記号 and 番号 from text.
Args:
text: Text to extract 記号番号 from
Returns:
A tuple of (記号, 番号) if both are found. A string of 番号 if 記号 does
not exist. `None` if nothing can be extracted.
"""
res = extract_one(KIGO_NUM, text)
# if res:
# print(1,text)
return res
def get_kigo(text: str) -> Union[str, None]:
"""Extracts 記号 from text.
Args:
text: Text to extract 記号 from
Returns:
A string of 記号 if it can be extracted, `None` otherwise.
"""
res = extract_one(KIGO_SINGLE, text)
return res
def get_num(text: str) -> Union[str, None]:
"""Extracts 番号 from text.
Args:
text: Text to extract 番号 from
Returns:
A string of 番号 if it can be extracted, `None` otherwise.
"""
res = extract_one(NUM_SINGLE, text)
return res
def find_one(match_func: Callable[[str], bool], texts: List[list]) -> list:
"""Finds one matched line given a matching function.
Args:
match_func: A function that takes a text, and returns `True` when matched,
and `False` otherwise.
texts: A list of textlines. Each element should also be a list whose last
element is text of the whole line.
Returns:
A matched element in texts. `None` if no match.
"""
for line in texts:
if match_func(line[-1]):
return line
return None
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,755
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/__init__.py
|
from .mynum_reader import MyNumReader
from .calibrator import Calibrator
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,756
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ws_reader.py
|
import json
import asyncio
import websockets
INFO = {
"Patient": {
"Birthday": {}
},
"Insurance": {
"HknjaNum": {},
'Kigo':{},
"Num": {},
'Branch': {},
'KofuYmd':{},
'YukoStYmd': {},
'YukoEdYmd': {},
'RouFtnKbn':{},
'Code':{},
}
}
async def ocr():
async with websockets.connect("ws://localhost:8766") as websocket:
#await websocket.send('{"Scan": "Insurance"}')
await websocket.send('{"Scan": "MyNumber"}')
#await websocket.send('{"Scan": "shuhoken"}')
res = await websocket.recv()
res = json.loads(res)
print(res)
await websocket.send(json.dumps(INFO))
res = await websocket.recv()
res = json.loads(res)
for meta_k, meta_v in res.items():
if isinstance(meta_v, dict):
for k, v in meta_v.items():
print(k, v["text"])
asyncio.get_event_loop().run_until_complete(ocr())
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,757
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/utils/image.py
|
"""Helper functions for image processing"""
from typing import List
import logging
import numpy as np
import cv2
def rotate_if_necessary(
img: np.ndarray,
threshold: int,
logger: logging.Logger
) -> np.ndarray:
"""Rotate image according to orientation and size.
Rotate image if small size is portrait or large size is landscape,
while small/large is defined by `threshold`
Args:
img: an image
threshold: Threshold of long size. Any image whose long size is longer than
threshold is considered large.
logger: a Python logger
Returns:
An image with fixed orientation
"""
if max(img.shape) > threshold:
if img.shape[1] > img.shape[0]:
img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
logger.info('Rotate large landscape image by 90 counterclockwise')
else:
if img.shape[0] > img.shape[1]:
img = cv2.rotate(img, cv2.ROTATE_90_COUNTERCLOCKWISE)
logger.info('Rotate small portrait image by 90 counterclockwise')
return img
def get_rect(polygons: np.ndarray, min_wh_ratio: float = 0) -> np.ndarray:
"""Gets rectangles from polygons.
Args:
polygons: 2d numpy array with a shape of (n, 8), where n is number of
polygons. If the 2nd dimension is larger than 8, only the first 8
numbers will be used.
min_wh_ratio: Minimum width-height ratio for a valid rectangle
Returns:
A 2d numpy array with a shape of (n, 4), where n is number of rectangles.
"""
polygons = polygons[:, :8]
rects = []
for polygon in polygons:
pts = polygon.reshape(4, 2)
x0, x1 = pts[:, 0].min(), pts[:, 0].max()
#y0, y1 = pts[:, 1].min(), pts[:, 1].max()
y0, y1 = pts[:2, 1].mean(), pts[2:, 1].mean()
if y1 - y0 < 8 or x1 - x0 < 8: continue
if (x1 - x0) / (y1 - y0) > min_wh_ratio:
rects.append([x0, y0, x1, y1])
rects = np.array(rects)
return rects
def get_chips(img: np.ndarray, boxes: np.ndarray) -> List[np.ndarray]:
"""Gets images chips from an image based on given bounding boxes.
Args:
img: Image to extract chips from
boxes: Bounding boxes
Returns:
A list of image chips, each of which is a numpy array.
"""
assert len(boxes.shape) == 2 and boxes.shape[1] == 4
assert (boxes >= 0).all(), 'expect all coords to be non-negative'
chips = []
for b in boxes.astype(int):
x1 = min(max(b[0], 0), img.shape[1] - 2)
x2 = max(b[2], x1 + 1)
y1 = min(max(b[1], 0), img.shape[0] - 2)
y2 = max(b[3], y1 + 1)
chips.append(img[y1:y2, x1:x2])
return chips
def merge(boxes: np.ndarray, viou_threshold: float = 0.6) -> List[np.ndarray]:
"""Merges overlapping or very close bounding boxes.
Args:
boxes: A numpy array with a shape of (n, 4), where n is number of boxes
viou_threshold: Threshold of IOU in vertial direction to determine if two
boxes should be considered for merging.
Returns:
A list of merged boxes.
"""
merged_boxes = []
skip = [False] * len(boxes)
for i in range(len(boxes)): #pylint: disable=consider-using-enumerate
if skip[i]: continue
b1 = boxes[i]
for j in range(i+1, len(boxes)):
if skip[j]: continue
b2 = boxes[j]
if (b2[0] < b1[0] < b2[2]) or (b1[0] < b2[0] < b1[2]):
v_iou = ((min(b1[3], b2[3]) - max(b1[1], b2[1])) /
(max(b1[3], b2[3]) - min(b1[1], b2[1])))
if v_iou > viou_threshold:
skip[j] = True
b1[0] = min(b1[0], b2[0])
b1[1] = min(b1[1], b2[1])
b1[2] = max(b1[2], b2[2])
b1[3] = max(b1[3], b2[3])
merged_boxes.append(b1)
return merged_boxes
def rotate(img, angle):
rot_m = cv2.getRotationMatrix2D((img.shape[1]//2, img.shape[0]//2), angle, 1)
out_shape = (img.shape[1], img.shape[0])
img = cv2.warpAffine(img, rot_m, out_shape, cv2.INTER_CUBIC)
return img
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,758
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/__init__.py
|
from .client_mock import ModelClientMock
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,759
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/finders/wide.py
|
import yaml
import numpy as np
from .. import match as m
from ..match import score
from .. import extract as e
class WideFinder(yaml.YAMLObject):
yaml_tag = u'!WideFinder'
def __init__(self, match_method, extract_method):
self.mf = getattr(m, match_method)
self.ef = getattr(e, extract_method)
self.scores = np.array([])
self.texts = []
def extract(self, texts):
self.scores, self.texts = score(self.mf, texts)
for idx in reversed(self.scores.argsort()):
if self.scores[idx] == 0: break
res = self.ef(self.texts[idx])
if res: return res
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,760
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/finders/kigo_num.py
|
"""A finder to extract 記号番号 from OCR results"""
from typing import List, Any
import yaml
from ..extract import get_kigo_num, get_kigo, get_num
def preprocess(line):
text = line[-1].replace('ー', '-').replace('一', '-')
return text
class KigoNumFinder(yaml.YAMLObject):
"""A finder class to extract 記号番号 from text lines output by OCR.
Typical usage example:
>>> finder = KigoNumFinder()
>>> res = finder.extract([[[], "記号123番号456"]])
>>> print(res["Kigo"])
123
>>> print(res["Num"])
456
"""
yaml_tag = u'!KigoNumFinder'
def extract(self, texts: List[List[Any]]) -> dict:
"""Extracts 記号番号 from text lines.
Args:
texts: OCR results in a list, each element of each has also to be a
list, each element of which is the text for each detected line.
Returns:
A dict with extracted Kigo and Num, value of each of which is `None`
if nothing can be extracted.
"""
self.info = {"Kigo": None, "Num": None}
texts = list(map(preprocess, texts))
# kigo num in the same line
for text in texts:
res = get_kigo_num(text)
if res is not None:
if isinstance(res, str): self.info["Num"] = res
if isinstance(res, tuple):
self.info["Kigo"] = res[0]
self.info["Num"] = res[1]
if self.info["Num"] is not None: return self.info
# kigo num in two lines
for idx in range(len(texts) - 1):
res_kigo = get_kigo(texts[idx])
res_num = get_num(texts[idx + 1])
if isinstance(res_kigo, str) and isinstance(res_num, str):
self.info["Kigo"] = res_kigo
self.info["Num"] = res_num
return self.info
return self.info
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,761
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/info_extractor/re_pattern.py
|
import regex as re
def re_compile(patterns):
if isinstance(patterns, str):
return re.compile(patterns)
if isinstance(patterns, list):
return list(map(re.compile, patterns))
if isinstance(patterns, dict):
return {k:re_compile(v) for k, v in patterns.items()}
raise TypeError(f"Unexpected type of patterns: {type(patterns)}")
BIRTHDAY = re_compile(r"生(年月日){e<3}")
INSURER = re_compile([
r"[^被]保(険者(番号|名称)){e<2}",
r"^[^被]?保(険者(番号|名称)){e<2}",
r"(公費負.*?番号){e<2}\d+",
# r"(公費負){e<2}担(?!資)",
r"(負担者番号){e<2}",
r"(機関名){e<2}"
])
KOHI_NUM = re_compile([
r"資格者\D{,3}番号{e<2}",
r"受給者\D{,3}番号{e<2}",
r"受給者\d",
r"(記号番号){e<2}"
r"(番号)"
])
KIGO = re_compile([
r"記号(.+)番号",
r"記号[^番]+$"
])
VALID_FROM = re_compile([
r"[発有]効期日{e<2}",
r"[発有]効開始{e<2}",
r"[発有]効年月日{e<2}",
r"適用開始{e<2}",
r"適用開始年月日{e<3}",
])
UNTIL_FIX = re_compile(r"(迄)(有効){e<2}")
VALID_UNTIL = re_compile([
r"有(効期限){e<2}",
r"喪失予定日{e<2}",
r"有効終了{e<2}",
])
KOFU_FIX = re_compile(r"[交茭].?[付苻]")
KOFU = re_compile([
r"交付年{e<2}",
r"発行年{e<2}",
r"(交\D?|\d\D?付)$"
])
SKKGET = re_compile([
r"資格取得{e<2}",
r"認定年月日{e<2}",
r"取得年月日{e<2}",
r"資格認定{e<2}",
r"扶養認定日{e<2}",
r"適用開始{e<2}",
r"適用開始年月日{e<2}",
r"該当年月日{e<2}",
])
MONTH_DATE = r"([\D-])(0[1-9]|[1-9]|1[0-2])([\D-])(0[1-9]|[1-9]|[1-2][0-9]0*|3[0-1]0*|99)(\D|$)"
DATE = re_compile({
"r": r"(令和|合和|令)(0[1-9]|[1-9]|[1-9][0-9])" + MONTH_DATE,
"h": r"(平成|平|成)(0[1-9]|[1-9]|[1-4][0-9])" + MONTH_DATE,
"s": r"(昭和|昭)(0[1-9]|[1-9]|[1-5][0-9]|6[0-4])" + MONTH_DATE,
"t": r"(大正|大|正)(0[1-9]|[1-9]|1[0-5])" + MONTH_DATE,
"m": r"(明治|明|治)(0[1-9]|[1-9]|[1-3][0-9]|4[0-5])" + MONTH_DATE,
"w": r"(19[0-9]{2}|2[0-9]{3})" + MONTH_DATE,
})
LAST_DAY = re.compile(r"[末未][日目]")
INSURER_NUM = re.compile(r"\d{6,8}")
ANY_NUM = re.compile(r"[\d-\pP]+")
DEDUCTIBLE_TAG = re.compile(r"(負担上限){e<3}")
DEDUCTIBLE_AMT = re.compile(r"([\do\pP]+)円")
DEDUCTIBLE_WITH_TAG = [
re.compile(r"[入人]院([\do\pP]+)円"),
re.compile(r"[入人]院外([\do\pP]+)円"),
re.compile(r"外来([\do\pP]+)円"),
re.compile(r"通院([\do\pP]+)円"),
re.compile(r"調剤([\do\pP]+)円")
]
DEDUCTIBLE_TAGS = [
"入院",
"入院外",
"外来",
"通院",
"調剤"
]
PERCENT_SINGLE_DIGIT = re.compile(r"(一部負担金){e<2}(\d)$")
PERCENT = re_compile(r"\d割")
PERCENT_TAG = re.compile(r"一部負担金{e<2}")
DIV_TAG = re.compile(r"(適用区分){e<2}")
KBN = re.compile(r"(区分\D{1,3})")
GEN = re.compile(r"(現役\D{1,3})")
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,762
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/model_serving/utils.py
|
import logging
import sys
from datetime import datetime
import numpy as np
def get_logger(config):
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger()
logger.handlers = []
logger.setLevel(getattr(logging, config.get('level', 'DEBUG')))
# stream
stream_handler = logging.StreamHandler(stream=sys.stdout)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
# file
log_path = config.get('path', None)
if log_path is not None:
log_folder = Path(__file__).parent.parent / log_path
if not log_folder.exists():
log_folder.mkdir(parents=True, exist_ok=True)
file_handler = logging.FileHandler(f"{log_folder}/{get_timestamp()}_scanner.log")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
def decode_img(pb):
img = np.frombuffer(pb.data, np.uint8)
img = img.reshape(pb.h, pb.w, pb.c)
return img
def get_timestamp():
timestamp = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
return timestamp
def get_dense_key(img):
w_resized = 32 / img.shape[0] * img.shape[1]
if w_resized > 512:
return 896
if w_resized > 256:
return 512
if w_resized > 128:
return 256
return 128
def get_layout(img):
layout = 'portrait' if img.shape[0] > img.shape[1] else 'landscape'
return layout
try:
import pyarmnn as ann
class ArmNNRuntime:
def __init__(self):
options = ann.CreationOptions()
self.runtime = ann.IRuntime(options)
self.infer_idx = 0
def get_infer_idx(self):
prev = self.infer_idx
self.infer_idx += 1
return prev
except ModuleNotFoundError:
print('PyArmNN is not installed')
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,763
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/camera/server.py
|
import queue
import threading
import time
import zmq
import cv2
import numpy as np
from utils import ensure_type
class CamServer:
def __init__(self, conf):
self.conf = conf
self.validate_conf()
self.cap = cv2.VideoCapture(conf["camera"]["path"])
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, conf["camera"]["width"])
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, conf["camera"]["height"])
self.cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, conf["camera"]["ae"])
self.cap.set(cv2.CAP_PROP_EXPOSURE, conf["camera"]["exposure"])
self.q = queue.Queue()
t = threading.Thread(target=self._reader)
t.daemon = True
t.start()
context = zmq.Context()
self.socket = context.socket(zmq.PUB)
self.socket.bind(f"tcp://127.0.0.1:{conf['zmq']['port']}")
def validate_conf(self):
cam = self.conf["camera"]
ensure_type(cam.get("path", None), str, "Invalid cam path")
ensure_type(cam.get("width", None), int, "Invalid cam width")
ensure_type(cam.get("height", None), int, "Invalid cam width")
if cam.get("ae", None) not in [1, 0]:
raise ValueError("Invalid cam AE")
ensure_type(cam.get("exposure", None), int, "Invalid cam width")
zmq = self.conf["zmq"]
ensure_type(zmq.get("port", None), int, "Invalid ZMQ port")
ensure_type(zmq.get("sleep", None), dict, "Invalid sleep conf")
ensure_type(zmq["sleep"].get("check", None), float, "Invalid check interval")
ensure_type(zmq["sleep"].get("flush", None), float, "Invalid flush interval")
def _reader(self):
while True:
t0 = time.time()
ret, img = self.cap.read()
t_cap = time.time()
if not ret:
break
if not self.q.empty():
try:
self.q.get_nowait()
except queue.Empty:
pass
self.q.put((t0, t_cap, img))
def start_pub(self):
while True:
t0, t_cap, img = self.q.get()
data = img.tobytes()
self.socket.send(data)
time.sleep(self.conf["zmq"]["sleep"]["flush"])
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,764
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/apps/utils/armnn.py
|
import pyarmnn as ann
class Runtime:
def __init__(self):
options = ann.CreationOptions()
self.runtime = ann.IRuntime(options)
self.infer_idx = 0
def get_infer_idx(self):
prev = self.infer_idx
self.infer_idx += 1
return prev
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,894,765
|
lin-hoshizora/mynumber
|
refs/heads/main
|
/ocr2/info_extractor/main_analyzer.py
|
"""Analyzer that extracts key information from OCR resutls of 主保険"""
from typing import List, Any
import regex as re
import numpy as np
from .finders import RouFtnKbnFinder, KigoNumFinder
from .analyzer_base import AnalyzerBase
from .extract import get_insurer_num, get_num
def preprocess(texts: List[List[Any]]):
"""Fixes some common issues in OCR results.
Args:
texts: OCR results in a list.
"""
for idx, line in enumerate(texts):
texts[idx][-1] = line[-1].replace("令和年", "令和元年")
# remove repeating 1
for idx, line in enumerate(texts):
if "保険者番号" not in line[-1] or "11" not in line[-1]:
continue
pos = line[-1].index("11")
probs = np.hstack([w[1] for w in line[:-1]])
if (min(probs[pos], probs[pos + 1]) < 0.7 and
max(probs[pos], probs[pos + 1]) > 0.9):
texts[idx][-1] = line[-1][:pos + 1] + line[-1][pos + 2:]
# add undetected hyphen
for idx, line in enumerate(texts):
if "記号" not in line[-1]:
continue
for w_idx, w1 in enumerate(line[:-2]):
w2 = line[w_idx + 1]
if (len(w1[0]) > 1 and len(w2[0]) > 1 and
w1[0].isdigit() and w2[0].isdigit()):
w1_right = w1[3][0] + w1[2][-1]
w2_left = w2[3][0] + w2[2][0]
gap_avg1 = (w1[2][1:] - w1[2][:-1]).mean()
gap_avg2 = (w2[2][1:] - w2[2][:-1]).mean()
gap_avg = (gap_avg1 + gap_avg2) / 2
if w2_left - w1_right > gap_avg * 3:
start = sum(len(w[0]) for w in line[:w_idx + 1])
texts[idx][-1] = line[-1][:start] + "-" + line[-1][start:]
for idx, line in enumerate(texts):
if ("番号" not in line[-1][:-4]):
continue
if not line[-1][-2:].isdigit():
continue
# add "枝番" for easier extraction if 番号 in the line, and the last box
# has only 2 digits
if (len(line) > 2 and len(line[-2][0]) == 2):
texts[idx][-1] = line[-1][:-2] + "枝番" + line[-1][-2:]
print('111111')
continue
# add "枝番" for easier extraction if the last 2 chars in the last box
# are digits and far away from other chars
if len(line[-2][0]) >= 4:
positions = line[-2][2]
pos_others = line[-2][2][:-2]
inter_other_avg = pos_others[1:] - pos_others[:-1]
space = positions[-2] - positions[-3]
if space > inter_other_avg.mean() * 2:
texts[idx][-1] = line[-1][:-2] + "枝番" + line[-1][-2:]
print('222222')
return texts
class MainAnalyzer(AnalyzerBase):
"""Analyzer to extract key information from OCR results of 主保険.
It tries to extract as much keyinformation as possible when `fit` is called.
The input argument `texts` of `fit` is a list containing OCR results, each
element of which also has to be a list, whose last element has to be text of
one line.
All extracted information is stored in info, and can be queried by tag via
`get`.
Typical usage example:
>>> analyzer = MainAnalyzer()
>>> analyzer.fit([["a str", "保険者番号12345678"], [["a list"], "記号1番号2"]])
>>> print(analyzer.get("HknajaNum"))
12345678
>>> print(analyzer.get("Kigo"))
1
>>> print(analyzer.get("Num"))
2
To add a new item as extraction target:
Add a finder in `config`. All finders in `config` will be called, and all
extracted information will be stored in `info`
To add fallback processing to catch patterns that cannot be handled by finders
in `config`:
It is recommended to add a new internal method can call it in `fit`. Check
`_handle_branch`, `_handle_hknjanum`, `_trim_hknjanum`, `_clean_kigo_num`
for examples.
"""
def __init__(self):
config = {
"HknjaNum": "wide_finder",
("Kigo", "Num"): KigoNumFinder(),
("Birthday", "YukoStYmd", "YukoEdYmd", "KofuYmd"): "dates_finder",
"Branch": "wide_finder",
"RouFtnKbn": RouFtnKbnFinder(),
}
super().__init__(config)
def _handle_branch(self, texts: List[List[Any]]):
"""Fallback handling when the corresponding finder cannnot extract Branch.
Args:
texts: OCR results in a list.
"""
# handle 番号 123 番123
if self._have("Branch"): return
for line in texts:
if "番号" not in line[-1]: continue
res = re.findall(r"番号\d+\(?番\)?(\d+)", line[-1])
# print(res, line[-1])
if res and res[0]:
self.info["Branch"] = res[0]
break
def _handle_kigo_num(self, texts: List[List[Any]]):
"""Fallback handling when Kigo, Num are seperated by another line
Args:
texts: OCR results in a list.
"""
if (self.info.get("Kigo", None) is not None or
self.info.get("Num", None) is not None):
return
for idx, line in enumerate(texts[:-2]):
if "記号" in line[-1] and "番号" in texts[idx + 2][-1]:
self.info["Kigo"] = line[-1][(line[-1].index("記号") + 2):]
self.info["Num"] = get_num(texts[idx + 2][-1])
break
def _clean_kigo_num(self):
for tag in ["Kigo", "Num"]:
if self.info.get(tag, None) is not None:
self.info[tag] = (self.info[tag].strip("・")
.strip("-")
.replace(".", ""))
if ("(" in self.info[tag] and ")" not in self.info[tag]) or "()" in self.info[tag]:
self.info[tag] = self.info[tag][:self.info[tag].index("(")]
def _handle_hknjanum(self, texts: List[List[Any]]):
"""Fallback handling when the corresponding finder cannnot extract HknjaNum.
Args:
texts: OCR results in a list.
"""
if self.info.get("HknjaNum", None) is not None: return
for line in texts[-2:]:
res = get_insurer_num(line[-1])
if res:
self.info["HknjaNum"] = res
break
if self.info.get("HknjaNum", None) is not None: return
for line in texts:
if line[-1].isdigit() and (len(line[-1]) == 8 or len(line[-1]) == 6):
self.info["HknjaNum"] = line[-1]
break
def _trim_hknjanum(self, texts: List[List[Any]]):
"""Truncates extracted HkanjaNum when necessary.
Args:
texts: OCR results in a list.
"""
num = self.info.get("HknjaNum", None)
if num is None: return
if len(num) < 7: return
all_text = "".join([l[-1] for l in texts])
if "国民健康保険" in all_text:
self.info["HknjaNum"] = num[:6]
else:
self.info["HknjaNum"] = num[:8]
def fit(self, texts: List[List[Any]]):
"""Extracts key information from OCR results.
Args:
texts: OCR results in a list.
"""
texts = preprocess(texts)
self._finder_fit(texts)
self._handle_hknjanum(texts)
self._trim_hknjanum(texts)
self._handle_branch(texts)
self._handle_kigo_num(texts)
self._clean_kigo_num()
|
{"/ocr2/info_extractor/kouhi_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/match.py", "/ocr2/info_extractor/extract.py", "/ocr2/info_extractor/analyzer_base.py"], "/ocr2/__init__.py": ["/ocr2/apps/__init__.py"], "/model_serving/models/__init__.py": ["/model_serving/models/dbnet_armnn.py", "/model_serving/models/dense8_armnn.py"], "/camera/client.py": ["/utils/__init__.py"], "/apps/mynum_reader.py": ["/apps/base_reader.py", "/apps/utils/general.py", "/apps/utils/text.py", "/info_extractor/date.py"], "/info_extractor/extract.py": ["/info_extractor/re_pattern.py", "/info_extractor/date.py"], "/apps/insurance_reader.py": ["/apps/base_reader.py", "/info_extractor/date.py"], "/ocr2/apps/__init__.py": ["/ocr2/apps/insurance_reader.py"], "/server.py": ["/apps/__init__.py", "/apps/insurance_reader.py", "/ocr2/info_extractor/main_analyzer.py", "/utils/__init__.py", "/camera/__init__.py", "/model_serving/__init__.py"], "/model_serving/models/dense8_armnn.py": ["/model_serving/models/dense8_base.py"], "/camera/__init__.py": ["/camera/client.py", "/camera/server.py"], "/model_serving/models/ctpnp_armnn.py": ["/model_serving/models/ctpnp_base.py"], "/utils/__init__.py": ["/utils/check.py", "/utils/log.py", "/utils/image.py", "/utils/conf.py"], "/ocr2/info_extractor/finders/date.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/utils/log.py": ["/utils/__init__.py"], "/info_extractor/finders/__init__.py": ["/info_extractor/finders/simple.py", "/info_extractor/finders/date.py", "/info_extractor/finders/wide.py", "/info_extractor/finders/jgngak.py"], "/info_extractor/finders/jgngak.py": ["/info_extractor/re_pattern.py"], "/apps/calibrator.py": ["/apps/base_reader.py"], "/info_extractor/analyzer.py": ["/info_extractor/finders/__init__.py", "/info_extractor/match.py", "/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/ocr2/info_extractor/finders/__init__.py": ["/ocr2/info_extractor/finders/simple.py", "/ocr2/info_extractor/finders/date.py", "/ocr2/info_extractor/finders/wide.py", "/ocr2/info_extractor/finders/jgngak.py", "/ocr2/info_extractor/finders/rouftnkbn.py", "/ocr2/info_extractor/finders/kigo_num.py"], "/ocr2/info_extractor/match.py": ["/ocr2/info_extractor/extract.py"], "/serve_cam.py": ["/camera/__init__.py"], "/info_extractor/finders/date.py": ["/info_extractor/match.py"], "/info_extractor/date.py": ["/info_extractor/re_pattern.py"], "/apps/simple_reader.py": ["/apps/base_reader.py"], "/ocr2/info_extractor/finders/simple.py": ["/ocr2/info_extractor/__init__.py"], "/model_serving/models/ctpnp_base.py": ["/model_serving/models/utils/image.py"], "/info_extractor/match.py": ["/info_extractor/extract.py", "/info_extractor/re_pattern.py"], "/model_serving/models/dense8_base.py": ["/model_serving/models/utils/general.py", "/model_serving/models/utils/image.py"], "/ocr2/info_extractor/__init__.py": ["/ocr2/info_extractor/main_analyzer.py", "/ocr2/info_extractor/kouhi_analyzer.py"], "/apps/phrase_locator.py": ["/apps/base_reader.py"], "/model_serving/client_mock.py": ["/model_serving/models/__init__.py", "/model_serving/utils.py"], "/ocr2/apps/insurance_reader.py": ["/ocr2/utils/image.py", "/ocr2/utils/general.py", "/ocr2/utils/text.py"], "/ocr2/info_extractor/finders/wide.py": ["/ocr2/info_extractor/__init__.py", "/ocr2/info_extractor/match.py"], "/ocr2/info_extractor/extract.py": ["/ocr2/info_extractor/date.py"], "/apps/__init__.py": ["/apps/mynum_reader.py", "/apps/calibrator.py"], "/model_serving/__init__.py": ["/model_serving/client_mock.py"], "/info_extractor/finders/wide.py": ["/info_extractor/match.py"], "/ocr2/info_extractor/finders/kigo_num.py": ["/ocr2/info_extractor/extract.py"], "/camera/server.py": ["/utils/__init__.py"], "/ocr2/info_extractor/main_analyzer.py": ["/ocr2/info_extractor/finders/__init__.py", "/ocr2/info_extractor/analyzer_base.py", "/ocr2/info_extractor/extract.py"]}
|
28,925,897
|
sidney-tio/rl-playground
|
refs/heads/master
|
/rl_networks.py
|
import torch.nn as nn
import torch.nn.functional as F
class ConvMLPNetwork(nn.Module):
""""CNN and MLP network to process OvercookedAI world_state.
Adapted from https://github.com/HumanCompatibleAI/human_aware_rl/blob/master/human_aware_rl/baselines_utils.py"""
def __init__(self, input_size, output_size, params):
super(ConvMLPNetwork, self).__init__()
num_hidden_layers = params["NUM_HIDDEN_LAYERS"]
size_hidden_layers = params["SIZE_HIDDEN_LAYERS"]
num_filters = params["NUM_FILTERS"]
num_convs = params["NUM_CONV_LAYERS"]
shape = params['OBS_STATE_SHAPE']
#Need to double check the padding and calculations
self.conv_initial = nn.Conv2d(input_size, num_filters, 5, padding = self.calculate_padding(5, 'same'))
self.conv_layers = nn.ModuleList([nn.Conv2d(num_filters, num_filters, kernel_size = 3, padding = self.calculate_padding(5, 'same')) for i in range(0,num_convs - 2)])
self.conv_final = nn.Conv2d(num_filters, num_filters, kernel_size = 3, padding = self.calculate_padding(3, 'valid'))
self.linear_initial = nn.Linear(shape[0] * shape[1] * num_filters, size_hidden_layers)
self.linear_layers = nn.ModuleList([nn.Linear(size_hidden_layers, size_hidden_layers) for i in range(num_hidden_layers)])
self.linear_final = nn.Linear(size_hidden_layers, output_size)
def forward(self, x):
x = self.conv_initial(x)
for convs in self.conv_layers:
x = F.leaky_relu(convs(x))
x = self.conv_final(x)
x = x.view(x.size()[0], -1)
x = self.linear_initial(x)
for linear in self.linear_layers:
x = F.leaky_relu(linear(x))
x = F.softmax(self.linear_final(x))
return x
def calculate_padding(self, kernel, pad_type):
if pad_type == 'valid':
return 0
if pad_type == 'same':
return int((kernel - 1) / 2)
|
{"/env.py": ["/rl_trainer.py"], "/rl_trainer.py": ["/ac_base.py", "/rl_networks.py"], "/ac_base.py": ["/rl_networks.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.