测试所有提取信息.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # @Author : bidikeji
  4. # @Time : 2021/1/11 0011 13:52
  5. '''
  6. Created on 2019年1月4日
  7. @author: User
  8. '''
  9. from bs4 import BeautifulSoup, Comment
  10. import copy
  11. import re
  12. import sys
  13. import os
  14. import codecs
  15. import requests
  16. import time
  17. _time1 = time.time()
  18. sys.path.append(os.path.abspath("../.."))
  19. import fool
  20. from BiddingKG.dl.interface.Connection import *
  21. from BiddingKG.dl.common.Utils import *
  22. from BiddingKG.dl.interface.Connection import getConnection
  23. import BiddingKG.dl.interface.predictor as predictor
  24. import BiddingKG.dl.interface.Preprocessing as Preprocessing
  25. import BiddingKG.dl.interface.getAttributes as getAttributes
  26. import BiddingKG.dl.entityLink.entityLink as entityLink
  27. import BiddingKG.dl.complaint.punish_predictor as punish_predictor
  28. # import BiddingKG.dl.complaint.punish_rule as punish_predictor
  29. import json
  30. '''
  31. doc_id = '3537ed94-9c7e-11e8-aed5-44a84246dbba'
  32. conn = psycopg2.connect(dbname="BiddingKG",user="postgres",password="postgres",host="192.168.2.101")
  33. cursor = conn.cursor()
  34. cursor.execute(" select content from articles where id='"+doc_id+"' ")
  35. row = cursor.fetchall()[0]
  36. #text = codecs.open("C:\\Users\\User\\Desktop\\1.html","r",encoding="utf8").read()
  37. #content = segment(tableToText(BeautifulSoup(row[0],"lxml")))
  38. '''
  39. ''''''
  40. codeNamePredict = predictor.CodeNamePredict()
  41. premPredict = predictor.PREMPredict()
  42. epcPredict = predictor.EPCPredict()
  43. roleRulePredict = predictor.RoleRulePredictor()
  44. timePredict = predictor.TimePredictor()
  45. # punish = punish_rule.Punish_Extract()
  46. punish = punish_predictor.Punish_Extract()
  47. productPredict = predictor.ProductPredictor()
  48. # 自定义jsonEncoder
  49. class MyEncoder(json.JSONEncoder):
  50. def default(self, obj):
  51. if isinstance(obj, np.ndarray):
  52. return obj.tolist()
  53. elif isinstance(obj, bytes):
  54. return str(obj, encoding='utf-8')
  55. elif isinstance(obj, (np.float_, np.float16, np.float32,
  56. np.float64)):
  57. return float(obj)
  58. elif isinstance(obj, str):
  59. return obj
  60. return json.JSONEncoder.default(self, obj)
  61. def predict(doc_id, text, title=""):
  62. list_articles, list_sentences, list_entitys, _ = Preprocessing.get_preprocessed([[doc_id, text, "", "", title]],
  63. useselffool=True)
  64. for articles in list_articles:
  65. print(articles.content)
  66. ''''''
  67. codeName = codeNamePredict.predict(list_sentences, list_entitys=list_entitys)
  68. print(codeName)
  69. premPredict.predict(list_sentences, list_entitys)
  70. # roleRulePredict.predict(list_articles,list_sentences, list_entitys,codeName)
  71. print("epcPredict")
  72. epcPredict.predict(list_sentences, list_entitys)
  73. print("entityLink")
  74. timePredict.predict(list_sentences, list_entitys)
  75. print("timePredict")
  76. entityLink.link_entitys(list_entitys)
  77. print("getPREMs")
  78. prem = getAttributes.getPREMs(list_sentences, list_entitys, list_articles)
  79. print("getPREMs")
  80. list_punish_dic = punish.get_punish_extracts(list_articles, list_sentences, list_entitys)
  81. product = productPredict.predict(list_sentences,list_entitys)
  82. for entitys in list_entitys:
  83. for entity in entitys:
  84. print(entity.entity_text, entity.entity_type, entity.label, entity.values, entity.sentence_index,
  85. entity.begin_index, entity.end_index, entity.wordOffset_begin, entity.wordOffset_end,entity.sentence_index)
  86. # print(prem)
  87. return json.dumps(Preprocessing.union_result(Preprocessing.union_result(Preprocessing.union_result(codeName, prem), list_punish_dic),product)[0],
  88. cls=MyEncoder, sort_keys=True, indent=4, ensure_ascii=False) # list_punish_dic
  89. def predict_back(doc_id, html):
  90. list_articles, list_sentences, list_entitys, _ = Preprocessing.get_preprocessed([[doc_id, html, "", "", ""]],
  91. useselffool=True)
  92. for articles in list_articles:
  93. print(articles.content)
  94. ''''''
  95. codeName = codeNamePredict.predict(list_sentences, list_entitys=list_entitys) #预测项目编号,名称
  96. print(codeName)
  97. premPredict.predict(list_sentences, list_entitys) # 角色金额模型
  98. roleRulePredict.predict(list_articles, list_sentences, list_entitys, codeName) # 角色规则
  99. print("epcPredict")
  100. epcPredict.predict(list_sentences, list_entitys) # 联系人模型
  101. print("entityLink")
  102. timePredict.predict(list_sentences, list_entitys) # 时间类别模型
  103. print("timePredict")
  104. entityLink.link_entitys(list_entitys) #
  105. print("getPREMs")
  106. prem = getAttributes.getPREMs(list_sentences, list_entitys, list_articles) # 找包,并包号与其他要素连接起来
  107. print("getPREMs")
  108. # punish_dic = punish.get_punish_extracts(list_sentences, list_entitys, title=title, text=list_articles[0].content)
  109. list_punish_dic = punish.get_punish_extracts(list_articles, list_sentences, list_entitys)
  110. # punish_dic = punish.get_punish_extracts(list_articles,list_sentences, list_entitys)
  111. # print(punish_dic)
  112. # prem[0][1]['punish'] = punish_dic
  113. # bidway = [] # 招标方式
  114. # moneySource = [] # 资金来源
  115. # servicetime = [] # 服务时间
  116. # time_release = [] # 发布时间
  117. # time_bidopen = [] # 开标时间
  118. # time_bidclose = [] # 截标时间
  119. # for entity in list_entitys[0]:
  120. # if entity.entity_type == 'bidway':
  121. # bidway.append(entity.entity_text)
  122. # elif entity.entity_type == 'moneySource':
  123. # moneySource.append(entity.entity_text)
  124. # elif entity.entity_type == 'servicetime':
  125. # servicetime.append(entity.entity_text)
  126. # elif entity.entity_type == 'time' and entity.label == 1:
  127. # time_release.append(entity.entity_text)
  128. # elif entity.entity_type == 'time' and entity.label == 2:
  129. # time_bidopen.append(entity.entity_text)
  130. # elif entity.entity_type == 'time' and entity.label == 3:
  131. # time_bidclose.append(entity.entity_text)
  132. #
  133. # prem[0][1]['bidway'] = ';'.join(set(bidway))
  134. # prem[0][1]['moneySource'] = ';'.join(set(moneySource))
  135. # prem[0][1]['servicetime'] = ';'.join(set(servicetime))
  136. # prem[0][1]['time_release'] = ';'.join(set(time_release))
  137. # prem[0][1]['time_bidopen'] = ';'.join(set(time_bidopen))
  138. # prem[0][1]['time_bidclose'] = ';'.join(set(time_bidclose))
  139. #
  140. # ''''''
  141. #
  142. # for entitys in list_entitys:
  143. # for entity in entitys:
  144. # print(entity.entity_text, entity.entity_type, entity.label, entity.values, entity.sentence_index,
  145. # entity.begin_index, entity.end_index, entity.wordOffset_begin, entity.wordOffset_end)
  146. #
  147. # print(prem)
  148. return json.dumps(Preprocessing.union_result(Preprocessing.union_result(codeName, prem), list_punish_dic)[0],
  149. cls=MyEncoder, sort_keys=True, indent=4, ensure_ascii=False)
  150. # return json.dumps(Preprocessing.union_result(codeName, prem)[0][1], cls=MyEncoder, sort_keys=True, indent=4,
  151. # ensure_ascii=False)
  152. def test(name, content):
  153. user = {
  154. "content": content,
  155. "id": name
  156. }
  157. myheaders = {'Content-Type': 'application/json'}
  158. _resp = requests.post("http://192.168.2.101:15015" + '/article_extract', json=user, headers=myheaders, verify=True)
  159. resp_json = _resp.content.decode("utf-8")
  160. print(resp_json)
  161. return resp_json
  162. if __name__ == "__main__":
  163. from tablestore import *
  164. endpoint = 'https://bxkc-ots.cn-hangzhou.ots.aliyuncs.com'
  165. access_key_id = 'LTAI4GJxbioV1y2WM3XcZTmP'
  166. access_key_secret = 'B3VITMoCnKtTQE6eAkDkat6UNFHped'
  167. instance_name = 'bxkc-ots'
  168. ots_client = OTSClient(endpoint, access_key_id, access_key_secret, instance_name)
  169. def get_data(query, max_rows, table_name='document',
  170. index_name='document_index',
  171. column_names=['docid', 'dochtmlcon','doctitle', 'info_type', 'page_time'],
  172. sorters=[FieldSort("page_time", SortOrder.DESC), FieldSort("docid", SortOrder.DESC)]):
  173. '''
  174. 从阿里云ots查询数据
  175. :param query: 查询命令
  176. :param max_rows: 最大返回多少数据
  177. :param table_name: 表名
  178. :param index_name: 表索引名
  179. :param column_names: 返回字段名
  180. :param sorters: 排序规则列表
  181. :return: 处理后的数据列表
  182. '''
  183. next_token = None
  184. data = []
  185. all_rows = []
  186. rows, next_token, total_count, is_all_succeed = \
  187. ots_client.search(table_name,
  188. index_name,
  189. SearchQuery(query,
  190. next_token=next_token,
  191. sort=Sort(sorters=sorters), # ASC升序
  192. limit=100,
  193. get_total_count=True),
  194. ColumnsToGet(column_names=column_names,
  195. return_type=ColumnReturnType.SPECIFIED))
  196. all_rows.extend(rows)
  197. while next_token:
  198. rows, next_token, total_count, is_all_succeed = \
  199. ots_client.search(table_name,
  200. index_name,
  201. SearchQuery(query,
  202. next_token=next_token,
  203. sort=None,
  204. limit=100,
  205. get_total_count=True),
  206. ColumnsToGet(column_names=column_names,
  207. return_type=ColumnReturnType.SPECIFIED))
  208. all_rows.extend(rows)
  209. if len(all_rows) > max_rows:
  210. print('已获取%d条数据' % len(all_rows))
  211. break
  212. if all_rows:
  213. for row in all_rows:
  214. tmp = []
  215. tmp.append(row[0][1][1])
  216. for tup in row[1]:
  217. tmp.append(tup[1])
  218. data.append(tmp)
  219. return data
  220. bool_query = TermQuery('docid','124113339')
  221. # bool_query = BoolQuery(
  222. # must_queries=[TermsQuery(field_name='info_type', column_values=['办公设备', '计算机设备']),
  223. # RangeQuery('page_time', range_from='2020-11-01', range_to='2020-11-31')]
  224. # )
  225. data = get_data(bool_query, 1)
  226. print(data)
  227. docid = str(data[0][0])
  228. html = data[0][1]
  229. title = data[0][2]
  230. # text = '中标候选人第1名:哈尔滨龙网电力设备有限公司,投标报价:19.98万元,质量,合格,工期/交货期/服务期:30天。\
  231. # 投诉处理公告,投诉人:张三。文章编号:京财采投字(2018)第42号。政府采购项目招标方式:公开招标,联系人:黎明。\
  232. # 建设资金来源及性质:资本金40%,自筹60%,,xx.=建设资金来源自筹,项目出资比例为100%,\
  233. # 二次供水泵房浊度仪进行国内组织公开招标采购,时间:2020-05-26,15:15:00,竞价结束时间:2020-05-26,15:45:00允许延时:是,'
  234. # docid = ""
  235. # html = '首都医科大学附属北京地坛医院1.5T核磁共振、16排CT和血管造影机维保服务医疗设备维修和保养服务采购项目政府采购合同公告'
  236. # html = '编号:厦财企〔2020〕12号,各有关单位:341号。处罚编号:厦财企〔2020〕12号,文章编号:京财采投字(2018)第42号。公告编号:闽建筑招〔2018〕5号。处罚编号:松公管监[2020]2号,'
  237. a = time.time()
  238. print("start")
  239. # print(predict('12',text))
  240. print(predict(docid, html,title=""))
  241. # test("12",text)
  242. print("takes", time.time() - a)
  243. pass