https://www.jianshu.com/p/9064ffe0f720
https://ai.qq.com/doc/nlpemo.shtml
# -*- coding: utf-8 -*- import hashlib import json from django.conf import settings # from django.utils import simplejson import re from .Sentiment_lstm import * import yaml from django.shortcuts import render # Create your views here. from keras.models import model_from_yaml from rest_framework.views import APIView from django.http import JsonResponse, HttpResponse import tensorflow as tf k_appid=100020 # Create your views here. print('loading model......') with open('api/lstm4_data//lstm.yml', 'r') as f: yaml_string = yaml.load(f) graph = tf.get_default_graph() model = model_from_yaml(yaml_string) print('loading weights......') model.load_weights('api/lstm4_data/lstm.h5') model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) print('已经开始工作') # def uni_str(a, encoding): # if isinstance(a, (list, tuple)): # s = [] # for i, k in enumerate(a): # s.append(uni_str(k, encoding)) # return s # elif isinstance(a, dict): # s = {} # for i, k in enumerate(a.items()): # key, value = k # s[uni_str(key, encoding)] = uni_str(value, encoding) # return s # elif isinstance(a, str) or (hasattr(a, '__str__') and callable(getattr(a, '__str__'))): # if getattr(a, '__str__'): # a = str(a) # return unicode(a, encoding) # elif isinstance(a, unicode): # return a # else: # return a class GetMessageView(APIView): def error_return(self, code, msg): return {"code": code, "msg": "{}".format(msg), "results": []} # get 请求 def get(self, request): # 获取参数数据 get = request.GET # 获取参数 a a = get.get('a') print(a) # 返回信息 d = { 'status': a, 'message': 'success', } return JsonResponse(d) def post(self, request): try: appkey = '243bca544bfea27b9c206171d8aafff6' response_body = request.body response_decode = response_body.decode() # response_decode=re.sub('\n','',response_decode) print('这里的c', response_decode) try: response_json = json.loads(response_decode) except: return JsonResponse(self.error_return(10000, '非法json格式')) print('这是response_json', response_json, type(response_json)) # and type(response_json.get('time_stamp'))==int and type(response_json['nonce_str'])==str and type(response_json['sign'])==str and type(response_json['text'])==list: print(type(response_json.get('appid'))) if type(response_json.get('appid')) != int: return JsonResponse(self.error_return(9990, '非法appId')) if response_json.get('appid') != 100020: return JsonResponse(self.error_return(9990, '非法appId')) if type(response_json.get('times')) != int: return JsonResponse(self.error_return(9991, '非法times')) if type(response_json.get('nstr')) != str: return JsonResponse(self.error_return(9992, '非法nstr')) if type(response_json.get('sign')) != str: return JsonResponse(self.error_return(9993, '非法sign')) str_ = (str(response_json.get('appId')) + str(response_json.get('times')) + response_json[ 'nstr'] + appkey) sign_server = md5_encode(str_) print(sign_server) if response_json['sign'] != sign_server: return JsonResponse(self.error_return(9994, '加密认证失败')) if type(response_json['texts']) != list: return JsonResponse(self.error_return(9995, '非法texts')) result = [] for my_data in response_json['texts']: if type(my_data) != dict and type(my_data['str']) != str and type(my_data['snu']) != int: return JsonResponse(self.error_return(9996, '非法text对象')) if len(my_data['str']) > 200: return JsonResponse(self.error_return(9997, '识别文本过长')) if type(my_data['snu']) != int: return JsonResponse(self.error_return(9998, '非法文本序号')) try: result.append(handler_text(my_data)) except Exception as e: print('9999错误码%s'%e) return JsonResponse(self.error_return(9999, '系统异常')) my_response = { 'code': 0, 'msg': '处理成功', 'results': result } return JsonResponse(my_response) except: return JsonResponse(self.error_return(9999, '系统异常')) # appkey='' # str_encode = (str(response_json.get('app_id')) + str(response_json.get('time_stamp')) + response_json['nonce_str']+appkey ).encode('utf8') # str_encode = hashlib.md5(str_encode).hexdigest() # print(str_encode) # if response_json['sign']==str_encode: # json_data = response_json.get('text') # print('这是json数据',json_data) # # json_data=re.sub('\n','',json_data) # # except: # # return JsonResponse(self.message_error) # if type(json_data)==list: # the_return={} # my_num=0 # for i in json_data: # my_num+=1 # print('我无语了',i,type(i)) # string=i[:200] # string, result, score=func(string) # response_my={ # 'ret':0, # 'msg':'ok', # 'data':{'text':string, # 'polar':result, # 'score':float(score)} # } # the_return[my_num]=response_my # print(the_return) # return JsonResponse(the_return) # else: # return JsonResponse(self.message_error) # else: # return JsonResponse({'msg':str_encode}) # else: # return JsonResponse({'msg':'1'}) # {"text": ["school_name", "西北农林科技大学", "school_id", "8", "school_name","西北大学", "school_id","6"]} # the_return={} # my_num=0 # for string in dict_data.values(): # my_num+=1 # print('这里的string是什么',string,type(string)) # string, result, score=func(string) # response_my={ # 'ret':0, # 'msg':'', # 'data':string, # 'polar':result, # 'score':float(score), # } # the_return[my_num]=response_my # return JsonResponse(the_return) # except Exception as e: # return HttpResponse(e) # return JsonResponse({'status':'fail'}) def handler_text(text): global graph with graph.as_default(): string = text.get('str') string = re_str(string) # print(string) # with open('kehushuju.txt', 'a') as gg: # gg.write(string + '\n') data = input_transform(string) score = model.predict(data) # print(score) # print(list(score)[0]) # print(type(list(score)[0])) result = model.predict_classes(data) if result[0][0] == 1: # print(string, ' 不敏感') result = 1 else: # print(string, ' 敏感') result = 0 results = { "snu": text.get('snu'), "polar": result, "confd": float(score) } with open('kehudata.txt', 'a')as f: f.write(text.get('str')) return results def md5_encode(string): string=string.encode('utf8') return hashlib.md5(string).hexdigest() # {"appid":12345,"times":1493468759,"nstr":"qww","sign":"ba55d8c912daaa927eddfdc83a100d86","texts":[{"str":"滚","snu":1},{"str":"哈哈哈","snu":2},{"str":"人才","snu":3944}]}