python +flask+ajax+百度图像识别接口实现图片异步上传转文字功能(进阶版)
py文件编写
from flask import Flask,render_template,request,jsonify
import requests,json,os,time
from aip import AipOcr
Basepath=os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
#图片上传处理程序
@app.route('/upload_img',methods=['POST'])
def upload_img():
img=request.files.get('img')
path=Basepath+'/static/uploads/'
img_path=path+img.filename
test_path='../static/uploads/'+img.filename
img.save(img_path)
return jsonify({'signal':1,'img_path':test_path})
#图像转文字页面路由配置
@app.route('/image-to-txt', methods=['GET'])
def image():
return render_template('image-to-txt.html')
@app.route('/image-to-txt', methods=['POST'])
def image2():
# 定义常量
APP_ID = '18093507'
API_KEY = 'OeQ8jbtBOjbcYjgWyZtF3SPY'
SECRET_KEY = '13x96WsNkr6TSOseWjtcjRO0nI0WsbkL'
# 初始化AipFace对象
aipOcr = AipOcr(APP_ID, API_KEY, SECRET_KEY)
# 读取图片
data = json.loads(request.form.get('data'))
word = data['word']
print('图片地址是'+word)
filePath = word
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
# 定义参数变量
options = {
'detect_direction': 'true',
'language_type': 'CHN_ENG',
}
# 调用通用文字识别接口
result = aipOcr.basicGeneral(get_file_content(filePath), options)
# print(json.dumps(result).encode('utf-8').decode("unicode-escape"))
res = json.dumps(result).encode('utf-8').decode("unicode-escape")
# print(eval(res)['words_result'])
# 通过eval函数转换成字典
# for word in eval(res)['words_result']:
# print(word['words'])
# print(eval(res)['words_result'])
try:
#json字符串
dic = json.dumps(eval(res)['words_result']).encode('utf-8').decode("unicode-escape")
list1 = []
#json.loads 将字符串转成字典格式
for d in json.loads(dic):
list1.append(d['words'])
result = '\r\n'.join(list1) #\r\n换行
print(result)
#结果写入记事本
tname = str(time.time()) #获取当前时间戳
txt = open('app/static/uploads/'+ tname +'.txt','w',encoding='utf-8')
txt.write(result)
txt.close()
return jsonify({"success": 200, "msg": "转换成功", "baiduocr": result,"txtname":tname})
except:
return jsonify({"success": 100, "msg": "转换失败", "baiduocr": "转换失败,可能是图像内容太复杂或者不清晰,换个图试试吧"})
if __name__ == '__main__':
app.run(debug=True) #FLASK开启调试模式,使程序修改即时生效
flask HTML文件编写
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>图片转文字-文字识别工具</title>
<link rel="stylesheet" href="../static/layui/css/layui.css">
<link rel="stylesheet" href="../static/style.css">
<script src="../static/jquery-3.4.1.min.js"></script>
<script src="../static/layui/layui.all.js"></script>
</head>
<body>
<style type="text/css">
.tips{padding: 20px 0px;}
#downtxt{margin-left: 20px;}
#downtxt a{color:#3D99F5; font-size: 16px; text-decoration: underline;}
</style>
<div style="width: 1200px; margin: 100px auto;">
<form class="layui-form" >
<!-- AJAX上传图片STAT-->
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">上传图片</label>
<div class="layui-input-block">
<input id="upload_input" class="admin img-fluid" type="file" onchange="changePicture(this)">
</div>
<div class="layui-input-block" style="margin-top: 20px;">
<img id="up_img" src="static/images/up2.png" style="width:30%;height: 30%" alt="mobile-image">
<input type="" id="saveurl" style="display: none;" name="" value="">
</div>
</div>
<!-- AJAX上传图片END-->
<div class="layui-form-item layui-form-text">
<label class="layui-form-label">转换结果</label>
<div class="layui-input-block">
<textarea placeholder="" class="layui-textarea result" style="height: 300px;"></textarea>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<div class="layui-btn fybtn" lay-submit lay-filter="*" >立即转换</div>
<button type="reset" class="layui-btn layui-btn-primary clearbtn">清空内容</button>
<span id="downtxt"></span>
</div>
</div>
</form>
<script src="layui.js"></script>
<script>
layui.use('form', function(){
var form = layui.form;
//各种基于事件的操作,下面会有进一步介绍
});
layui.use('layer', function(){
var layer = layui.layer;
});
</script>
</div>
<script type="text/javascript">
function changePicture() {
//图片实时预览
var readfile=new FileReader();
var f=document.getElementById('upload_input').files[0];
readfile.readAsDataURL(f);
readfile.onload=function (e) {
document.getElementById('up_img').src=this.result;
}
//上传文件到服务器空间STAT
var formData=new FormData();
var f=document.getElementById('upload_input').files[0];
formData.append('img',f)
$.ajax({
url:"{{ url_for('upload_img') }}",
data:formData,
cache:false,
processData:false,
contentType:false,
type:'POST',
success:function (data) {
if(data.signal==1){
layer.msg('上传成功');
document.getElementById('saveurl').value=data.img_path;
}
}
})
//上传文件到服务器空间END
}
</script>
<script type="text/javascript">
//点击转换
$(function(){
$('.fybtn').click(function(){
var index = layer.load();
urls1 = $('#saveurl').val();
urls2 = urls1.replace('..','app') //要在虚拟环境下运行,要不图片路径报错
var word = urls2;
var data= {
data: JSON.stringify({
'word': word,
}),
}
$.ajax({
type: 'POST',
url: '/image-to-txt',
data: data, // 这个data是要post的数据
success: function(data){ // 这个data是接收到的响应的实体
layer.close(index);
$('.result').val(data['baiduocr']);
document.getElementById('downtxt').innerHTML='下载转换结果txt格式:<a href="/static/uploads/'+%20data['txtname']%20+'.txt" target="_blank">'+ data['txtname'] +'.txt</a>'
}
});
});
});
//点击清空输入框
$('.clearbtn').on('click',function () {
$('.result').html('');
$('.txt').html('');
})
</script>
</body>
</html>
欢迎留下你的看法
共 0 条评论