Utils.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. '''
  2. Created on 2018年12月20日
  3. @author: User
  4. '''
  5. import numpy as np
  6. import re
  7. import gensim
  8. from keras import backend as K
  9. import os,sys
  10. import time
  11. import traceback
  12. from threading import RLock
  13. # from pai_tf_predict_proto import tf_predict_pb2
  14. import requests
  15. model_w2v = None
  16. lock_model_w2v = RLock()
  17. USE_PAI_EAS = False
  18. Lazy_load = False
  19. # API_URL = "http://192.168.2.103:8802"
  20. API_URL = "http://127.0.0.1:888"
  21. # USE_API = True
  22. USE_API = False
  23. def getCurrent_date(format="%Y-%m-%d %H:%M:%S"):
  24. _time = time.strftime(format,time.localtime())
  25. return _time
  26. def getw2vfilepath():
  27. filename = "wiki_128_word_embedding_new.vector"
  28. w2vfile = getFileFromSysPath(filename)
  29. if w2vfile is not None:
  30. return w2vfile
  31. return filename
  32. def getLazyLoad():
  33. global Lazy_load
  34. return Lazy_load
  35. def getFileFromSysPath(filename):
  36. for _path in sys.path:
  37. if os.path.isdir(_path):
  38. for _file in os.listdir(_path):
  39. _abspath = os.path.join(_path,_file)
  40. if os.path.isfile(_abspath):
  41. if _file==filename:
  42. return _abspath
  43. return None
  44. model_word_file = os.path.dirname(__file__)+"/../singlew2v_model.vector"
  45. model_word = None
  46. lock_model_word = RLock()
  47. from decimal import Decimal
  48. import logging
  49. logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  50. logger = logging.getLogger(__name__)
  51. import pickle
  52. import os
  53. import json
  54. #自定义jsonEncoder
  55. class MyEncoder(json.JSONEncoder):
  56. def __init__(self):
  57. import numpy as np
  58. global np
  59. def default(self, obj):
  60. if isinstance(obj, np.ndarray):
  61. return obj.tolist()
  62. elif isinstance(obj, bytes):
  63. return str(obj, encoding='utf-8')
  64. elif isinstance(obj, (np.float_, np.float16, np.float32,
  65. np.float64)):
  66. return float(obj)
  67. elif isinstance(obj,(np.int64,np.int32)):
  68. return int(obj)
  69. return json.JSONEncoder.default(self, obj)
  70. vocab_word = None
  71. vocab_words = None
  72. file_vocab_word = "vocab_word.pk"
  73. file_vocab_words = "vocab_words.pk"
  74. selffool_authorization = "NjlhMWFjMjVmNWYyNzI0MjY1OGQ1M2Y0ZmY4ZGY0Mzg3Yjc2MTVjYg=="
  75. selffool_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/selffool_gpu"
  76. selffool_seg_authorization = "OWUwM2Q0ZmE3YjYxNzU4YzFiMjliNGVkMTA3MzJkNjQ2MzJiYzBhZg=="
  77. selffool_seg_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/selffool_seg_gpu"
  78. codename_authorization = "Y2M5MDUxMzU1MTU4OGM3ZDk2ZmEzYjkxYmYyYzJiZmUyYTgwYTg5NA=="
  79. codename_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/codename_gpu"
  80. form_item_authorization = "ODdkZWY1YWY0NmNhNjU2OTI2NWY4YmUyM2ZlMDg1NTZjOWRkYTVjMw=="
  81. form_item_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/form"
  82. person_authorization = "N2I2MDU2N2Q2MGQ0ZWZlZGM3NDkyNTA1Nzc4YmM5OTlhY2MxZGU1Mw=="
  83. person_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/person"
  84. role_authorization = "OWM1ZDg5ZDEwYTEwYWI4OGNjYmRlMmQ1NzYwNWNlZGZkZmRmMjE4OQ=="
  85. role_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/role"
  86. money_authorization = "MDQyNjc2ZDczYjBhYmM4Yzc4ZGI4YjRmMjc3NGI5NTdlNzJiY2IwZA=="
  87. money_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/money"
  88. codeclasses_authorization = "MmUyNWIxZjQ2NjAzMWJlMGIzYzkxMjMzNWY5OWI3NzJlMWQ1ZjY4Yw=="
  89. codeclasses_url = "http://pai-eas-vpc.cn-beijing.aliyuncs.com/api/predict/codeclasses"
  90. def viterbi_decode(score, transition_params):
  91. """Decode the highest scoring sequence of tags outside of TensorFlow.
  92. This should only be used at test time.
  93. Args:
  94. score: A [seq_len, num_tags] matrix of unary potentials.
  95. transition_params: A [num_tags, num_tags] matrix of binary potentials.
  96. Returns:
  97. viterbi: A [seq_len] list of integers containing the highest scoring tag
  98. indices.
  99. viterbi_score: A float containing the score for the Viterbi sequence.
  100. """
  101. trellis = np.zeros_like(score)
  102. backpointers = np.zeros_like(score, dtype=np.int32)
  103. trellis[0] = score[0]
  104. for t in range(1, score.shape[0]):
  105. v = np.expand_dims(trellis[t - 1], 1) + transition_params
  106. trellis[t] = score[t] + np.max(v, 0)
  107. backpointers[t] = np.argmax(v, 0)
  108. viterbi = [np.argmax(trellis[-1])]
  109. for bp in reversed(backpointers[1:]):
  110. viterbi.append(bp[viterbi[-1]])
  111. viterbi.reverse()
  112. viterbi_score = np.max(trellis[-1])
  113. return viterbi, viterbi_score
  114. def limitRun(sess,list_output,feed_dict,MAX_BATCH=1024):
  115. len_sample = 0
  116. if len(feed_dict.keys())>0:
  117. len_sample = len(feed_dict[list(feed_dict.keys())[0]])
  118. if len_sample>MAX_BATCH:
  119. list_result = [[] for _ in range(len(list_output))]
  120. _begin = 0
  121. while(_begin<len_sample):
  122. new_dict = dict()
  123. for _key in feed_dict.keys():
  124. if isinstance(feed_dict[_key],(float,int,np.int32,np.float_,np.float16,np.float32,np.float64)):
  125. new_dict[_key] = feed_dict[_key]
  126. else:
  127. new_dict[_key] = feed_dict[_key][_begin:_begin+MAX_BATCH]
  128. _output = sess.run(list_output,feed_dict=new_dict)
  129. for _index in range(len(list_output)):
  130. list_result[_index].extend(_output[_index])
  131. _begin += MAX_BATCH
  132. else:
  133. list_result = sess.run(list_output,feed_dict=feed_dict)
  134. return list_result
  135. def get_values(response,output_name):
  136. """
  137. Get the value of a specified output tensor
  138. :param output_name: name of the output tensor
  139. :return: the content of the output tensor
  140. """
  141. output = response.outputs[output_name]
  142. if output.dtype == tf_predict_pb2.DT_FLOAT:
  143. _value = output.float_val
  144. elif output.dtype == tf_predict_pb2.DT_INT8 or output.dtype == tf_predict_pb2.DT_INT16 or \
  145. output.dtype == tf_predict_pb2.DT_INT32:
  146. _value = output.int_val
  147. elif output.dtype == tf_predict_pb2.DT_INT64:
  148. _value = output.int64_val
  149. elif output.dtype == tf_predict_pb2.DT_DOUBLE:
  150. _value = output.double_val
  151. elif output.dtype == tf_predict_pb2.DT_STRING:
  152. _value = output.string_val
  153. elif output.dtype == tf_predict_pb2.DT_BOOL:
  154. _value = output.bool_val
  155. return np.array(_value).reshape(response.outputs[output_name].array_shape.dim)
  156. def vpc_requests(url,authorization,request_data,list_outputs):
  157. headers = {"Authorization": authorization}
  158. dict_outputs = dict()
  159. response = tf_predict_pb2.PredictResponse()
  160. resp = requests.post(url, data=request_data, headers=headers)
  161. if resp.status_code != 200:
  162. print(resp.status_code,resp.content)
  163. log("调用pai-eas接口出错,authorization:"+str(authorization))
  164. return None
  165. else:
  166. response = tf_predict_pb2.PredictResponse()
  167. response.ParseFromString(resp.content)
  168. for _output in list_outputs:
  169. dict_outputs[_output] = get_values(response, _output)
  170. return dict_outputs
  171. def encodeInput(data,word_len,word_flag=True,userFool=False):
  172. result = []
  173. out_index = 0
  174. for item in data:
  175. if out_index in [0]:
  176. list_word = item[-word_len:]
  177. else:
  178. list_word = item[:word_len]
  179. temp = []
  180. if word_flag:
  181. for word in list_word:
  182. if userFool:
  183. temp.append(getIndexOfWord_fool(word))
  184. else:
  185. temp.append(getIndexOfWord(word))
  186. list_append = []
  187. temp_len = len(temp)
  188. while(temp_len<word_len):
  189. if userFool:
  190. list_append.append(0)
  191. else:
  192. list_append.append(getIndexOfWord("<pad>"))
  193. temp_len += 1
  194. if out_index in [0]:
  195. temp = list_append+temp
  196. else:
  197. temp = temp+list_append
  198. else:
  199. for words in list_word:
  200. temp.append(getIndexOfWords(words))
  201. list_append = []
  202. temp_len = len(temp)
  203. while(temp_len<word_len):
  204. list_append.append(getIndexOfWords("<pad>"))
  205. temp_len += 1
  206. if out_index in [0,1]:
  207. temp = list_append+temp
  208. else:
  209. temp = temp+list_append
  210. result.append(temp)
  211. out_index += 1
  212. return result
  213. def encodeInput_form(input,MAX_LEN=30):
  214. x = np.zeros([MAX_LEN])
  215. for i in range(len(input)):
  216. if i>=MAX_LEN:
  217. break
  218. x[i] = getIndexOfWord(input[i])
  219. return x
  220. def getVocabAndMatrix(model,Embedding_size = 60):
  221. '''
  222. @summary:获取子向量的词典和子向量矩阵
  223. '''
  224. vocab = ["<pad>"]+model.index2word
  225. embedding_matrix = np.zeros((len(vocab),Embedding_size))
  226. for i in range(1,len(vocab)):
  227. embedding_matrix[i] = model[vocab[i]]
  228. return vocab,embedding_matrix
  229. def getIndexOfWord(word):
  230. global vocab_word,file_vocab_word
  231. if vocab_word is None:
  232. if os.path.exists(file_vocab_word):
  233. vocab = load(file_vocab_word)
  234. vocab_word = dict((w, i) for i, w in enumerate(np.array(vocab)))
  235. else:
  236. model = getModel_word()
  237. vocab,_ = getVocabAndMatrix(model, Embedding_size=60)
  238. vocab_word = dict((w, i) for i, w in enumerate(np.array(vocab)))
  239. save(vocab,file_vocab_word)
  240. if word in vocab_word.keys():
  241. return vocab_word[word]
  242. else:
  243. return vocab_word['<pad>']
  244. def changeIndexFromWordToWords(tokens,word_index):
  245. '''
  246. @summary:转换某个字的字偏移为词偏移
  247. '''
  248. before_index = 0
  249. after_index = 0
  250. for i in range(len(tokens)):
  251. after_index = after_index+len(tokens[i])
  252. if before_index<=word_index and after_index>word_index:
  253. return i
  254. before_index = after_index
  255. return i+1
  256. def getIndexOfWords(words):
  257. global vocab_words,file_vocab_words
  258. if vocab_words is None:
  259. if os.path.exists(file_vocab_words):
  260. vocab = load(file_vocab_words)
  261. vocab_words = dict((w, i) for i, w in enumerate(np.array(vocab)))
  262. else:
  263. model = getModel_w2v()
  264. vocab,_ = getVocabAndMatrix(model, Embedding_size=128)
  265. vocab_words = dict((w, i) for i, w in enumerate(np.array(vocab)))
  266. save(vocab,file_vocab_words)
  267. if words in vocab_words.keys():
  268. return vocab_words[words]
  269. else:
  270. return vocab_words["<pad>"]
  271. def log(msg):
  272. '''
  273. @summary:打印信息
  274. '''
  275. logger.info(msg)
  276. def debug(msg):
  277. '''
  278. @summary:打印信息
  279. '''
  280. logger.debug(msg)
  281. def save(object_to_save, path):
  282. '''
  283. 保存对象
  284. @Arugs:
  285. object_to_save: 需要保存的对象
  286. @Return:
  287. 保存的路径
  288. '''
  289. with open(path, 'wb') as f:
  290. pickle.dump(object_to_save, f)
  291. def load(path):
  292. '''
  293. 读取对象
  294. @Arugs:
  295. path: 读取的路径
  296. @Return:
  297. 读取的对象
  298. '''
  299. with open(path, 'rb') as f:
  300. object1 = pickle.load(f)
  301. return object1
  302. fool_char_to_id = load(os.path.dirname(__file__)+"/fool_char_to_id.pk")
  303. def getIndexOfWord_fool(word):
  304. if word in fool_char_to_id.keys():
  305. return fool_char_to_id[word]
  306. else:
  307. return fool_char_to_id["[UNK]"]
  308. def find_index(list_tofind,text):
  309. '''
  310. @summary: 查找所有词汇在字符串中第一次出现的位置
  311. @param:
  312. list_tofind:待查找词汇
  313. text:字符串
  314. @return: list,每个词汇第一次出现的位置
  315. '''
  316. result = []
  317. for item in list_tofind:
  318. index = text.find(item)
  319. if index>=0:
  320. result.append(index)
  321. else:
  322. result.append(-1)
  323. return result
  324. def combine(list1,list2):
  325. '''
  326. @summary:将两个list中的字符串两两拼接
  327. @param:
  328. list1:字符串list
  329. list2:字符串list
  330. @return:拼接结果list
  331. '''
  332. result = []
  333. for item1 in list1:
  334. for item2 in list2:
  335. result.append(str(item1)+str(item2))
  336. return result
  337. def getDigitsDic(unit):
  338. '''
  339. @summary:拿到中文对应的数字
  340. '''
  341. DigitsDic = {"零":0, "壹":1, "贰":2, "叁":3, "肆":4, "伍":5, "陆":6, "柒":7, "捌":8, "玖":9,
  342. "〇":0, "一":1, "二":2, "三":3, "四":4, "五":5, "六":6, "七":7, "八":8, "九":9}
  343. return DigitsDic.get(unit)
  344. def getMultipleFactor(unit):
  345. '''
  346. @summary:拿到单位对应的值
  347. '''
  348. MultipleFactor = {"兆":Decimal(1000000000000),"亿":Decimal(100000000),"万":Decimal(10000),"仟":Decimal(1000),"千":Decimal(1000),"佰":Decimal(100),"百":Decimal(100),"拾":Decimal(10),"十":Decimal(10),"元":Decimal(1),"圆":Decimal(1),"角":round(Decimal(0.1),1),"分":round(Decimal(0.01),2)}
  349. return MultipleFactor.get(unit)
  350. def getUnifyMoney(money):
  351. '''
  352. @summary:将中文金额字符串转换为数字金额
  353. @param:
  354. money:中文金额字符串
  355. @return: decimal,数据金额
  356. '''
  357. MAX_MONEY = 1000000000000
  358. MAX_NUM = 12
  359. #去掉逗号
  360. money = re.sub("[,,]","",money)
  361. money = re.sub("[^0-9.零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]","",money)
  362. result = Decimal(0)
  363. chnDigits = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]
  364. # chnFactorUnits = ["兆", "亿", "万", "仟", "佰", "拾","圆","元","角","分"]
  365. chnFactorUnits = ["圆", "元","兆", "亿", "万", "仟", "佰", "拾", "角", "分", '十', '百', '千']
  366. LowMoneypattern = re.compile("^[\d,]+(\.\d+)?$")
  367. BigMoneypattern = re.compile("^零?(?P<BigMoney>[%s])$"%("".join(chnDigits)))
  368. try:
  369. if re.search(LowMoneypattern,money) is not None:
  370. return Decimal(money)
  371. elif re.search(BigMoneypattern,money) is not None:
  372. return getDigitsDic(re.search(BigMoneypattern,money).group("BigMoney"))
  373. for factorUnit in chnFactorUnits:
  374. if re.search(re.compile(".*%s.*"%(factorUnit)),money) is not None:
  375. subMoneys = re.split(re.compile("%s(?!.*%s.*)"%(factorUnit,factorUnit)),money)
  376. if re.search(re.compile("^(\d+)(\.\d+)?$"),subMoneys[0]) is not None:
  377. if MAX_MONEY/getMultipleFactor(factorUnit)<Decimal(subMoneys[0]):
  378. return Decimal(0)
  379. result += Decimal(subMoneys[0])*(getMultipleFactor(factorUnit))
  380. elif len(subMoneys[0])==1:
  381. if re.search(re.compile("^[%s]$"%("".join(chnDigits))),subMoneys[0]) is not None:
  382. result += Decimal(getDigitsDic(subMoneys[0]))*(getMultipleFactor(factorUnit))
  383. # subMoneys[0]中无金额单位,不可再拆分
  384. elif subMoneys[0]=="":
  385. result += 0
  386. elif re.search(re.compile("[%s]"%("".join(chnFactorUnits))),subMoneys[0]) is None:
  387. # print(subMoneys)
  388. # subMoneys[0] = subMoneys[0][0]
  389. result += Decimal(getUnifyMoney(subMoneys[0])) * (getMultipleFactor(factorUnit))
  390. else:
  391. result += Decimal(getUnifyMoney(subMoneys[0]))*(getMultipleFactor(factorUnit))
  392. if len(subMoneys)>1:
  393. if re.search(re.compile("^(\d+(,)?)+(\.\d+)?[百千万亿]?\s?(元)?$"),subMoneys[1]) is not None:
  394. result += Decimal(subMoneys[1])
  395. elif len(subMoneys[1])==1:
  396. if re.search(re.compile("^[%s]$"%("".join(chnDigits))),subMoneys[1]) is not None:
  397. result += Decimal(getDigitsDic(subMoneys[1]))
  398. else:
  399. result += Decimal(getUnifyMoney(subMoneys[1]))
  400. break
  401. except Exception as e:
  402. # traceback.print_exc()
  403. return Decimal(0)
  404. return result
  405. def getModel_w2v():
  406. '''
  407. @summary:加载词向量
  408. '''
  409. global model_w2v,lock_model_w2v
  410. with lock_model_w2v:
  411. if model_w2v is None:
  412. model_w2v = gensim.models.KeyedVectors.load_word2vec_format(getw2vfilepath(),binary=True)
  413. return model_w2v
  414. def getModel_word():
  415. '''
  416. @summary:加载字向量
  417. '''
  418. global model_word,lock_model_w2v
  419. with lock_model_word:
  420. if model_word is None:
  421. model_word = gensim.models.KeyedVectors.load_word2vec_format(model_word_file,binary=True)
  422. return model_word
  423. # getModel_w2v()
  424. # getModel_word()
  425. def findAllIndex(substr,wholestr):
  426. '''
  427. @summary: 找到字符串的子串的所有begin_index
  428. @param:
  429. substr:子字符串
  430. wholestr:子串所在完整字符串
  431. @return: list,字符串的子串的所有begin_index
  432. '''
  433. copystr = wholestr
  434. result = []
  435. indexappend = 0
  436. while(True):
  437. index = copystr.find(substr)
  438. if index<0:
  439. break
  440. else:
  441. result.append(indexappend+index)
  442. indexappend += index+len(substr)
  443. copystr = copystr[index+len(substr):]
  444. return result
  445. def spanWindow(tokens,begin_index,end_index,size,center_include=False,word_flag = False,use_text = False,text = None):
  446. '''
  447. @summary:取得某个实体的上下文词汇
  448. @param:
  449. tokens:句子分词list
  450. begin_index:实体的开始index
  451. end_index:实体的结束index
  452. size:左右两边各取多少个词
  453. center_include:是否包含实体
  454. word_flag:词/字,默认是词
  455. @return: list,实体的上下文词汇
  456. '''
  457. if use_text:
  458. assert text is not None
  459. length_tokens = len(tokens)
  460. if begin_index>size:
  461. begin = begin_index-size
  462. else:
  463. begin = 0
  464. if end_index+size<length_tokens:
  465. end = end_index+size+1
  466. else:
  467. end = length_tokens
  468. result = []
  469. if not word_flag:
  470. result.append(tokens[begin:begin_index])
  471. if center_include:
  472. if use_text:
  473. result.append(text)
  474. else:
  475. result.append(tokens[begin_index:end_index+1])
  476. result.append(tokens[end_index+1:end])
  477. else:
  478. result.append("".join(tokens[begin:begin_index]))
  479. if center_include:
  480. if use_text:
  481. result.append(text)
  482. else:
  483. result.append("".join(tokens[begin_index:end_index+1]))
  484. result.append("".join(tokens[end_index+1:end]))
  485. #print(result)
  486. return result
  487. #根据规则补全编号或名称两边的符号
  488. def fitDataByRule(data):
  489. symbol_dict = {"(":")",
  490. "(":")",
  491. "[":"]",
  492. "【":"】",
  493. ")":"(",
  494. ")":"(",
  495. "]":"[",
  496. "】":"【"}
  497. leftSymbol_pattern = re.compile("[\((\[【]")
  498. rightSymbol_pattern = re.compile("[\))\]】]")
  499. leftfinds = re.findall(leftSymbol_pattern,data)
  500. rightfinds = re.findall(rightSymbol_pattern,data)
  501. result = data
  502. if len(leftfinds)+len(rightfinds)==0:
  503. return data
  504. elif len(leftfinds)==len(rightfinds):
  505. return data
  506. elif abs(len(leftfinds)-len(rightfinds))==1:
  507. if len(leftfinds)>len(rightfinds):
  508. if symbol_dict.get(data[0]) is not None:
  509. result = data[1:]
  510. else:
  511. #print(symbol_dict.get(leftfinds[0]))
  512. result = data+symbol_dict.get(leftfinds[0])
  513. else:
  514. if symbol_dict.get(data[-1]) is not None:
  515. result = data[:-1]
  516. else:
  517. result = symbol_dict.get(rightfinds[0])+data
  518. result = re.sub("[。]","",result)
  519. return result
  520. from datetime import date
  521. # 时间合法性判断
  522. def isValidDate(year, month, day):
  523. try:
  524. date(year, month, day)
  525. except:
  526. return False
  527. else:
  528. return True
  529. time_format_pattern = re.compile("((?P<year>20\d{2}|\d{2}|二[零〇0][零〇一二三四五六七八九0]{2})\s*[-/年.]\s*(?P<month>\d{1,2}|[一二三四五六七八九十]{1,3})\s*[-/月.]\s*(?P<day>\d{1,2}|[一二三四五六七八九十]{1,3}))")
  530. from BiddingKG.dl.ratio.re_ratio import getUnifyNum
  531. def timeFormat(_time):
  532. current_year = time.strftime("%Y",time.localtime())
  533. all_match = re.finditer(time_format_pattern,_time)
  534. for _match in all_match:
  535. if len(_match.group())>0:
  536. legal = True
  537. year = ""
  538. month = ""
  539. day = ""
  540. for k,v in _match.groupdict().items():
  541. if k=="year":
  542. year = v
  543. if k=="month":
  544. month = v
  545. if k=="day":
  546. day = v
  547. if year!="":
  548. if re.search("^\d+$",year):
  549. if len(year)==2:
  550. year = "20"+year
  551. if int(year)>int(current_year):
  552. legal = False
  553. else:
  554. _year = ""
  555. for word in year:
  556. if word == '0':
  557. _year += word
  558. else:
  559. _year += str(getDigitsDic(word))
  560. year = _year
  561. else:
  562. legal = False
  563. if month!="":
  564. if re.search("^\d+$", month):
  565. if int(month)>12:
  566. legal = False
  567. else:
  568. month = int(getUnifyNum(month))
  569. if month>=1 and month<=12:
  570. month = str(month)
  571. else:
  572. legal = False
  573. else:
  574. legal = False
  575. if day!="":
  576. if re.search("^\d+$", day):
  577. if int(day)>31:
  578. legal = False
  579. else:
  580. day = int(getUnifyNum(day))
  581. if day >= 1 and day <= 31:
  582. day = str(day)
  583. else:
  584. legal = False
  585. else:
  586. legal = False
  587. # print(year,month,day)
  588. if not isValidDate(int(year),int(month),int(day)):
  589. legal = False
  590. if legal:
  591. return "%s-%s-%s"%(year,month.rjust(2,"0"),day.rjust(2,"0"))
  592. return ""
  593. def embedding(datas,shape):
  594. '''
  595. @summary:查找词汇对应的词向量
  596. @param:
  597. datas:词汇的list
  598. shape:结果的shape
  599. @return: array,返回对应shape的词嵌入
  600. '''
  601. model_w2v = getModel_w2v()
  602. embed = np.zeros(shape)
  603. length = shape[1]
  604. out_index = 0
  605. #print(datas)
  606. for data in datas:
  607. index = 0
  608. for item in data:
  609. item_not_space = re.sub("\s*","",item)
  610. if index>=length:
  611. break
  612. if item_not_space in model_w2v.vocab:
  613. embed[out_index][index] = model_w2v[item_not_space]
  614. index += 1
  615. else:
  616. #embed[out_index][index] = model_w2v['unk']
  617. index += 1
  618. out_index += 1
  619. return embed
  620. def embedding_word(datas,shape):
  621. '''
  622. @summary:查找词汇对应的词向量
  623. @param:
  624. datas:词汇的list
  625. shape:结果的shape
  626. @return: array,返回对应shape的词嵌入
  627. '''
  628. model_w2v = getModel_word()
  629. embed = np.zeros(shape)
  630. length = shape[1]
  631. out_index = 0
  632. #print(datas)
  633. for data in datas:
  634. index = 0
  635. for item in str(data)[-shape[1]:]:
  636. if index>=length:
  637. break
  638. if item in model_w2v.vocab:
  639. embed[out_index][index] = model_w2v[item]
  640. index += 1
  641. else:
  642. # embed[out_index][index] = model_w2v['unk']
  643. index += 1
  644. out_index += 1
  645. return embed
  646. def embedding_word_forward(datas,shape):
  647. '''
  648. @summary:查找词汇对应的词向量
  649. @param:
  650. datas:词汇的list
  651. shape:结果的shape
  652. @return: array,返回对应shape的词嵌入
  653. '''
  654. model_w2v = getModel_word()
  655. embed = np.zeros(shape)
  656. length = shape[1]
  657. out_index = 0
  658. #print(datas)
  659. for data in datas:
  660. index = 0
  661. for item in str(data)[:shape[1]]:
  662. if index>=length:
  663. break
  664. if item in model_w2v.vocab:
  665. embed[out_index][index] = model_w2v[item]
  666. index += 1
  667. else:
  668. # embed[out_index][index] = model_w2v['unk']
  669. index += 1
  670. out_index += 1
  671. return embed
  672. def formEncoding(text,shape=(100,60),expand=False):
  673. embedding = np.zeros(shape)
  674. word_model = getModel_word()
  675. for i in range(len(text)):
  676. if i>=shape[0]:
  677. break
  678. if text[i] in word_model.vocab:
  679. embedding[i] = word_model[text[i]]
  680. if expand:
  681. embedding = np.expand_dims(embedding,0)
  682. return embedding
  683. def partMoney(entity_text,input2_shape = [7]):
  684. '''
  685. @summary:对金额分段
  686. @param:
  687. entity_text:数值金额
  688. input2_shape:分类数
  689. @return: array,分段之后的独热编码
  690. '''
  691. money = float(entity_text)
  692. parts = np.zeros(input2_shape)
  693. if money<100:
  694. parts[0] = 1
  695. elif money<1000:
  696. parts[1] = 1
  697. elif money<10000:
  698. parts[2] = 1
  699. elif money<100000:
  700. parts[3] = 1
  701. elif money<1000000:
  702. parts[4] = 1
  703. elif money<10000000:
  704. parts[5] = 1
  705. else:
  706. parts[6] = 1
  707. return parts
  708. def uniform_num(num):
  709. d1 = {'一': '1', '二': '2', '三': '3', '四': '4', '五': '5', '六': '6', '七': '7', '八': '8', '九': '9', '十': '10'}
  710. # d2 = {'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5', 'F': '6', 'G': '7', 'H': '8', 'I': '9', 'J': '10'}
  711. d3 = {'Ⅰ': '1', 'Ⅱ': '2', 'Ⅲ': '3', 'Ⅳ': '4', 'Ⅴ': '5', 'Ⅵ': '6', 'Ⅶ': '7'}
  712. if num.isdigit():
  713. if re.search('^0[\d]$', num):
  714. num = num[1:]
  715. return num
  716. elif re.search('^[一二三四五六七八九十]+$', num):
  717. _digit = re.search('^[一二三四五六七八九十]+$', num).group(0)
  718. if len(_digit) == 1:
  719. num = d1[_digit]
  720. elif len(_digit) == 2 and _digit[0] == '十':
  721. num = '1'+ d1[_digit[1]]
  722. elif len(_digit) == 2 and _digit[1] == '十':
  723. num = d1[_digit[0]] + '0'
  724. elif len(_digit) == 3 and _digit[1] == '十':
  725. num = d1[_digit[0]] + d1[_digit[2]]
  726. elif re.search('[ⅠⅡⅢⅣⅤⅥⅦ]', num):
  727. num = re.search('[ⅠⅡⅢⅣⅤⅥⅦ]', num).group(0)
  728. num = d3[num]
  729. return num
  730. def uniform_package_name(package_name):
  731. '''
  732. 统一规范化包号。数值类型统一为阿拉伯数字,字母统一为大写,包含施工监理等抽到前面, 例 A包监理一标段 统一为 监理A1 ; 包Ⅱ 统一为 2
  733. :param package_name: 字符串类型 包号
  734. :return:
  735. '''
  736. package_name_raw = package_name
  737. package_name = re.sub('pdf|doc|docs|xlsx|rar|\d{4}年', ' ', package_name)
  738. package_name = package_name.replace('标段(包)', '标段').replace('№', '')
  739. package_name = re.sub('\[|【', '', package_name)
  740. kw = re.search('(施工|监理|监测|勘察|设计|劳务)', package_name)
  741. name = ""
  742. if kw:
  743. name += kw.group(0)
  744. if re.search('^[a-zA-Z0-9-]{5,}$', package_name): # 五个字符以上编号
  745. _digit = re.search('^[a-zA-Z0-9-]{5,}$', package_name).group(0).upper()
  746. # print('规范化包号1', _digit)
  747. name += _digit
  748. elif re.search('(?P<eng>[a-zA-Z])包[:)]?第?(?P<num>([0-9]{1,4}|[一二三四五六七八九十]{1,4}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,4}))标段?', package_name): # 处理类似 A包2标段
  749. ser = re.search('(?P<eng>[a-zA-Z])包[:)]?第?(?P<num>([0-9]{1,4}|[一二三四五六七八九十]{1,4}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,4}))标段?', package_name)
  750. # print('规范化包号2', ser.group(0))
  751. _char = ser.groupdict().get('eng')
  752. if _char:
  753. _char = _char.upper()
  754. _digit = ser.groupdict().get('num')
  755. _digit = uniform_num(_digit)
  756. name += _char.upper() + _digit
  757. elif re.search('第?(?P<eng>[0-9a-zA-Z-]{1,4})?(?P<num>([0-9]{1,4}|[一二三四五六七八九十]{1,4}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,4}))(标[段号的包项]?|合同[包段]|([分子]?[包标]))', package_name): # 处理类似 A包2标段
  758. ser = re.search('第?(?P<eng>[0-9a-zA-Z-]{1,4})?(?P<num>([0-9]{1,4}|[一二三四五六七八九十]{1,4}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,4}))(标[段号的包项]?|合同[包段]|([分子]?[包标]))', package_name)
  759. # print('规范化包号3', ser.group(0))
  760. _char = ser.groupdict().get('eng')
  761. if _char:
  762. _char = _char.upper()
  763. _digit = ser.groupdict().get('num')
  764. _digit = uniform_num(_digit)
  765. if _char:
  766. name += _char.upper()
  767. name += _digit
  768. elif re.search('(标[段号的包项]?|项目|子项目?|([分子]?包|包[组件号]))编?号?[::]?(?P<eng>[0-9a-zA-Z-]{1,4})?(?P<num>([0-9]{1,4}|[一二三四五六七八九十]{1,4}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,4}))', package_name): # 数字的统一的阿拉伯数字
  769. ser = re.search('(标[段号的包项]?|项目|子项目?|([分子]?包|包[组件号]))编?号?[::]?(?P<eng>[0-9a-zA-Z-]{1,4})?(?P<num>([0-9]{1,4}|[一二三四五六七八九十]{1,4}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,4}))',package_name)
  770. # print('规范化包号4', ser.group(0))
  771. _char = ser.groupdict().get('eng')
  772. if _char:
  773. _char = _char.upper()
  774. _digit = ser.groupdict().get('num')
  775. _digit = uniform_num(_digit)
  776. if _char:
  777. name += _char.upper()
  778. name += _digit
  779. elif re.search('(标[段号的包项]|([分子]?包|包[组件号]))编?号?[::]?(?P<eng>[a-zA-Z-]{1,5})', package_name): # 数字的统一的阿拉伯数字
  780. _digit = re.search('(标[段号的包项]|([分子]?包|包[组件号]))编?号?[::]?(?P<eng>[a-zA-Z-]{1,5})', package_name).group('eng').upper()
  781. # print('规范化包号5', _digit)
  782. name += _digit
  783. elif re.search('(?P<eng>[a-zA-Z]{1,4})(标[段号的包项]|([分子]?[包标]|包[组件号]))', package_name): # 数字的统一的阿拉伯数字
  784. _digit = re.search('(?P<eng>[a-zA-Z]{1,4})(标[段号的包项]|([分子]?[包标]|包[组件号]))', package_name).group('eng').upper()
  785. # print('规范化包号6', _digit)
  786. name += _digit
  787. elif re.search('^([0-9]{1,4}|[一二三四五六七八九十]{1,4}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,4})$', package_name): # 数字的统一的阿拉伯数字
  788. _digit = re.search('^([0-9]{1,4}|[一二三四五六七八九十]{1,4}|[ⅠⅡⅢⅣⅤⅥⅦ]{1,4})$', package_name).group(0)
  789. # print('规范化包号7', _digit)
  790. _digit = uniform_num(_digit)
  791. name += _digit
  792. elif re.search('^[a-zA-Z0-9-]+$', package_name):
  793. _char = re.search('^[a-zA-Z0-9-]+$', package_name).group(0)
  794. # print('规范化包号8', _char)
  795. name += _char.upper()
  796. if name == "":
  797. return package_name_raw
  798. else:
  799. if name.isdigit():
  800. name = str(int(name))
  801. # print('原始包号:%s, 处理后:%s'%(package_name, name))
  802. return name
  803. def money_process(money_text, header):
  804. '''
  805. 输入金额文本及金额列表头,返回统一数字化金额及金额单位
  806. :param money_text:金额字符串
  807. :param header:金额列表头,用于提取单位
  808. :return:
  809. '''
  810. money = 0
  811. money_unit = ""
  812. re_price = re.search("[零壹贰叁肆伍陆柒捌玖拾佰仟萬億圆十百千万亿元角分]{3,}|\d[\d,]*(?:\.\d+)?[((]?万?", money_text)
  813. if re_price:
  814. money_text = re_price.group(0)
  815. if '万元' in header and '万' not in money_text:
  816. money_text += '万元'
  817. money = float(getUnifyMoney(money_text))
  818. if money > 10000000000000: # 大于万亿的去除
  819. money = 0
  820. money_unit = '万元' if '万' in money_text else '元'
  821. return (money, money_unit)
  822. def recall(y_true, y_pred):
  823. '''
  824. 计算召回率
  825. @Argus:
  826. y_true: 正确的标签
  827. y_pred: 模型预测的标签
  828. @Return
  829. 召回率
  830. '''
  831. c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
  832. c3 = K.sum(K.round(K.clip(y_true, 0, 1)))
  833. if c3 == 0:
  834. return 0
  835. recall = c1 / c3
  836. return recall
  837. def f1_score(y_true, y_pred):
  838. '''
  839. 计算F1
  840. @Argus:
  841. y_true: 正确的标签
  842. y_pred: 模型预测的标签
  843. @Return
  844. F1值
  845. '''
  846. c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
  847. c2 = K.sum(K.round(K.clip(y_pred, 0, 1)))
  848. c3 = K.sum(K.round(K.clip(y_true, 0, 1)))
  849. precision = c1 / c2
  850. if c3 == 0:
  851. recall = 0
  852. else:
  853. recall = c1 / c3
  854. f1_score = 2 * (precision * recall) / (precision + recall)
  855. return f1_score
  856. def precision(y_true, y_pred):
  857. '''
  858. 计算精确率
  859. @Argus:
  860. y_true: 正确的标签
  861. y_pred: 模型预测的标签
  862. @Return
  863. 精确率
  864. '''
  865. c1 = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
  866. c2 = K.sum(K.round(K.clip(y_pred, 0, 1)))
  867. precision = c1 / c2
  868. return precision
  869. # def print_metrics(history):
  870. # '''
  871. # 制作每次迭代的各metrics变化图片
  872. #
  873. # @Arugs:
  874. # history: 模型训练迭代的历史记录
  875. # '''
  876. # import matplotlib.pyplot as plt
  877. #
  878. # # loss图
  879. # loss = history.history['loss']
  880. # val_loss = history.history['val_loss']
  881. # epochs = range(1, len(loss) + 1)
  882. # plt.subplot(2, 2, 1)
  883. # plt.plot(epochs, loss, 'bo', label='Training loss')
  884. # plt.plot(epochs, val_loss, 'b', label='Validation loss')
  885. # plt.title('Training and validation loss')
  886. # plt.xlabel('Epochs')
  887. # plt.ylabel('Loss')
  888. # plt.legend()
  889. #
  890. # # f1图
  891. # f1 = history.history['f1_score']
  892. # val_f1 = history.history['val_f1_score']
  893. # plt.subplot(2, 2, 2)
  894. # plt.plot(epochs, f1, 'bo', label='Training f1')
  895. # plt.plot(epochs, val_f1, 'b', label='Validation f1')
  896. # plt.title('Training and validation f1')
  897. # plt.xlabel('Epochs')
  898. # plt.ylabel('F1')
  899. # plt.legend()
  900. #
  901. # # precision图
  902. # prec = history.history['precision']
  903. # val_prec = history.history['val_precision']
  904. # plt.subplot(2, 2, 3)
  905. # plt.plot(epochs, prec, 'bo', label='Training precision')
  906. # plt.plot(epochs, val_prec, 'b', label='Validation pecision')
  907. # plt.title('Training and validation precision')
  908. # plt.xlabel('Epochs')
  909. # plt.ylabel('Precision')
  910. # plt.legend()
  911. #
  912. # # recall图
  913. # recall = history.history['recall']
  914. # val_recall = history.history['val_recall']
  915. # plt.subplot(2, 2, 4)
  916. # plt.plot(epochs, recall, 'bo', label='Training recall')
  917. # plt.plot(epochs, val_recall, 'b', label='Validation recall')
  918. # plt.title('Training and validation recall')
  919. # plt.xlabel('Epochs')
  920. # plt.ylabel('Recall')
  921. # plt.legend()
  922. #
  923. # plt.show()
  924. if __name__=="__main__":
  925. # print(fool_char_to_id[">"])
  926. print(getUnifyMoney('伍仟贰佰零壹拾伍万零捌佰壹拾元陆角伍分'))
  927. # model = getModel_w2v()
  928. # vocab,matrix = getVocabAndMatrix(model, Embedding_size=128)
  929. # save([vocab,matrix],"vocabMatrix_words.pk")