Files
ocr/main.py
2023-11-16 06:25:12 +08:00

70 lines
2.1 KiB
Python

import io
import oss2
import requests
from PIL import Image, ImageFile
# 读取 .env
from dotenv import dotenv_values
config = dotenv_values(".env")
ImageFile.LOAD_TRUNCATED_IMAGES = True
# 下载图片(使用OSS下载)
def download_image(url:str) -> Image:
if url.startswith('http://image.gameuiux.cn/') or url.startswith('https://image.gameuiux.cn/'):
try:
url = url.replace('http://image.gameuiux.cn/', '').replace('https://image.gameuiux.cn/', '')
oss2.defaults.connection_pool_size = 100
oss_auth = oss2.Auth(config['OSS_ACCESS_KEY_ID'], config['OSS_ACCESS_KEY_SECRET'])
return Image.open(io.BytesIO(oss2.Bucket(oss_auth, f'http://{config["OSS_HOST"]}', config['OSS_BUCKET_NAME']).get_object(url).read()))
except Exception:
print('图片下载失败:', url)
return None
else:
try:
response = requests.get(url)
return Image.open(io.BytesIO(response.content))
except Exception:
print('图片下载失败:', url)
return None
import pymysql
import pymysql.cursors
import cnocr
ocr = cnocr.CnOcr(rec_model_name='ch_PP-OCRv3')
conn = pymysql.connect(host=config['MYSQL_HOST'], user=config['MYSQL_USER'], password=config['MYSQL_PASSWORD'], database=config['MYSQL_NAME'], cursorclass=pymysql.cursors.DictCursor)
cursor = conn.cursor()
cursor.execute("SELECT id, content FROM web_images LIMIT 5")
# 获取查询结果
rows = cursor.fetchall()
for row in rows:
#print(row)
image = download_image(row['content'])
if image is None:
print('图片下载失败,跳过')
continue
out = ocr.ocr(image)
# 这段代码将只包含那些非空、不是纯数字且长度大于1的'text'值
texts = [item['text'] for item in out if item['text'] and not item['text'].isdigit() and len(item['text']) > 1]
print(texts)
# 关闭游标和连接
cursor.close()
conn.close()
'''
from cnocr import CnOcr
img_fp = './x.jpg'
ocr = CnOcr(rec_model_name='ch_PP-OCRv3') # 所有参数都使用默认值
out = ocr.ocr(img_fp)
print(out)
'''