Ai
1 Star 2 Fork 0

闪电侠的右手/算法小合集-移动开发作业

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
test_restful.py 6.00 KB
一键复制 编辑 原始数据 按行查看 历史
from flask import Flask, request, jsonify
from utils import restful
from utils.deblur import deblur_image
from utils.couplet import coup
from utils.genres.complete import final_model as completeMusicModel
from utils.genres.split import final_model as splitMusicModel
from utils.genres import feature_extract
from flask_cors import *
import base64
import numpy as np
import cv2
import re
import jieba
from io import BytesIO
from PIL import Image
from wordcloud import WordCloud, ImageColorGenerator
import config
import os
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
# CORS(app=app, supports_credentials=True)
f=open(config.stopwords,"r")
stopwords={}.fromkeys(f.read().split("\n"))
f.close()
#加载用户自定义词典
jieba.load_userdict(config.user_dict)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route("/api/couplet", methods=['GET'])
def couplet():
up = request.args.get('up')
print(up)
return jsonify({
"up":up,
"down":coup(up)
})
@app.route("/api/image/face_detection", methods=["POST"])
def face_detection():
print("hello")
base = request.json["base64"]
base = re.sub('^data:image/.+;base64,', '', base)
img = base64.b64decode(base)
nparr = np.fromstring(img,np.uint8)
img=cv2.imdecode(nparr,cv2.COLOR_RGB2BGR)
img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # 必须要经过一次转换最后在转到HSV,否则颜色空间出错
h,s,v = cv2.split(img)
img_face = np.zeros(shape=(img.shape[0], img.shape[1]))
h_low, h_up, s_low, s_up, v_low, v_up = 0, 30, 30, 220, 90, 255
img_face[(v >= v_low) * (v <= v_up) * (h >= h_low) * (h <= h_up) * (s >= s_low) * (s <= s_up)] = 255
image_encode = cv2.imencode('.jpg', img_face) # (True, array([[255],[216], [255],...,[138],
base64_data = str(base64.b64encode(image_encode[1])) # b'/9j/4AAQSK...
data = "data:image/jpg;base64,"+base64_data[2:-1]
return jsonify({
"msg": "succss",
"data": data
})
@app.route("/api/nlp/genwordcloud", methods=["POST"])
def genwordcloud():
specifiedWords = request.json['specifiedWords']
text = request.json['text']
maskBackgroundImageBase64 = request.json['maskBackgroundImageBase64']
#强调特殊名词
for sw in specifiedWords.split(','):
jieba.suggest_freq((sw), True)
segs=jieba.cut(text)
mytext_list=[]
#文本清洗
for seg in segs:
if seg not in stopwords and seg!=" ":
mytext_list.append(seg.replace(" ",""))
cloud_text=",".join(mytext_list)
base64_data = re.sub('^data:image/.+;base64,', '', maskBackgroundImageBase64)
byte_data = base64.b64decode(base64_data)
image_data = BytesIO(byte_data)
img = np.array(Image.open(image_data))
wc = WordCloud(background_color="white", mask=img,max_words=2000,font_path="C:\Windows\Fonts\STFANGSO.TTF",min_font_size=1,max_font_size=60, stopwords=None)
wc.generate(cloud_text)
wc_img = wc.to_array()
image_encode = cv2.imencode('.jpg', wc_img) # (True, array([[255],[216], [255],...,[138],
base64_data = str(base64.b64encode(image_encode[1])) # b'/9j/4AAQSK...
data = "data:image/jpg;base64,"+base64_data[2:-1]
return jsonify({
'data': data
})
@app.route("/api/image/deblur", methods=['POST'])
def deblur():
width = request.json['width']
height = request.json['height']
base64str = request.json['base64']
base64str = re.sub('^data:image/.+;base64,', '', base64str)
bytestr = base64.b64decode(base64str)
image = Image.open(BytesIO(bytestr))
deblured_img = np.array(deblur_image.deblur(image).resize((width, height)))
image_encode = cv2.imencode('.jpg',deblured_img)
base64_data = str(base64.b64encode(image_encode[1])) # b'/9j/4AAQSK...
data = "data:image/jpg;base64," + base64_data[2:-1]
return jsonify({
"data": data
})
def ToFile(base64data, file=r"E:\python_project\test_restful\music.wav"):
try:
ori_image_data = base64.b64decode(base64data)
fout = open(file, 'wb')
fout.write(ori_image_data)
fout.close()
print("success")
return True
except Exception as e:
print(e)
return False
@app.route("/api/signal/genres", methods=['POST'])
def genres():
data = request.json['data']
# print(data)
result = ToFile(data)
if result:
a = request.json['a']
a = float(a) if a else 0.08
b = request.json['b']
b = float(b) if b else 0.05
slice = request.json['slice']
print(a, b, type(a), type(b), slice, type(slice))
file = os.path.join(config.dir, "music.wav")
print(file)
mfcc, logfbank = feature_extract.Processsor(file, a, b, slice).run()
if not slice: # 不切片
model = completeMusicModel.CompleteModel([config.genres_complete_mfcc, config.genres_complete_logfbank]).get_final_model()
p = model.predict({'mfcc_input': np.expand_dims(mfcc, axis=1),'attention_logbank_input': np.expand_dims(logfbank, axis=1)})[0].astype(float)/2
else:
model = splitMusicModel.SplitModel([config.genres_split_mfcc, config.genres_split_logfbank]).get_final_model()
p = model.predict({'mfcc_input': np.expand_dims(mfcc, axis=1),'attention_logbank_input': np.expand_dims(logfbank, axis=1)}).astype(float)/2
p = np.around(np.average(p, axis=0), decimals=4)
probability = jsonify({"result":[
{"name":"blues", "prob": round(p[0], 4)},
{"name":"classical", "prob": round(p[1], 4)},
{"name":"country", "prob": round(p[2], 4)},
{"name":"disco", "prob": round(p[3], 4)},
{"name":"hiphop", "prob": round(p[4], 4)},
{"name":"jazz", "prob": round(p[5], 4)},
{"name":"metal", "prob": round(p[6], 4)},
{"name":"pop", "prob": round(p[7], 4)},
{"name":"reggae", "prob": round(p[8], 4)},
{"name":"rock", "prob": round(p[9], 4)},
]})
return probability
return "hello"
if __name__ == '__main__':
app.run(port=8888)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/shaoeric/algorithm_heji.git
git@gitee.com:shaoeric/algorithm_heji.git
shaoeric
algorithm_heji
算法小合集-移动开发作业
master

搜索帮助