parseCreditPdf.py0810 160 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276
  1. #coding=utf-8
  2. import shutil
  3. import pdfplumber
  4. import pandas as pd
  5. import numpy as np;
  6. import sys
  7. import os
  8. import traceback
  9. from prp import PrpCrypt
  10. #指标相关
  11. import loanIndexParser as lip;
  12. import payRcdIndexParser as prp;
  13. import creditCardIndexParser as cip
  14. import queryInfoIndexParser as qip
  15. import requests
  16. import utils;
  17. import time;
  18. import consts;
  19. import math
  20. import dfParser;
  21. import gc
  22. import json
  23. from dbController import DbController
  24. from pboc.invokePboc import PBOC
  25. from ini_op import Config;
  26. base_dir = os.path.dirname(os.path.abspath(__file__))
  27. config = Config(base_dir+"/config.ini");
  28. productNumJz = config.get("baseconf","productNumJz")
  29. productNumXxw = config.get("baseconf","productNumXxw")
  30. productNumXy = config.get("baseconf", "productNumXy")
  31. #连接数据库
  32. dbController = DbController();
  33. pd.set_option('mode.chained_assignment', None)
  34. import log
  35. logger = log.logger
  36. import xyHttp
  37. # 查询信息
  38. dfMap = {};
  39. allHeaders = [] # 所有表头
  40. queryInfoDf = pd.DataFrame();
  41. queryInfoDf_header = ["被查询者姓名", "被查询者证件类型", "被查询者证件号码", "查询机构", "查询原因"];
  42. dfMap["queryInfoDf"] = {"df": queryInfoDf, "nextDf": None};
  43. allHeaders.append(queryInfoDf_header);
  44. # 身份信息
  45. identityDf = pd.DataFrame();
  46. identity_header = ['性别', '出生日期', '婚姻状况', '学历', '学位', '就业状况', '国籍', '电子邮箱']
  47. addressDf = pd.DataFrame(); # 通讯地址
  48. dfMap["identityDf"] = {"df": identityDf, "nextDf": None, "mobiles": None};
  49. allHeaders.append(identity_header);
  50. # 配偶信息
  51. mateDf = pd.DataFrame();
  52. mateDf_header = ['姓名', '证件类型', '证件号码', '工作单位', '联系电话']
  53. dfMap["mateDf"] = {"df": mateDf, "nextDf": None};
  54. allHeaders.append(mateDf_header);
  55. # 居住信息====暂时该信息没有用到先不解析
  56. liveInfoDf = pd.DataFrame();
  57. liveInfoDf_header = ['编号', '居住地址', '住宅电话', '居住状况', '信息更新日期']
  58. dfMap["liveInfoDf"] = {"df": liveInfoDf, "nextDf": None};
  59. allHeaders.append(liveInfoDf_header);
  60. # 职业信息
  61. occupationDf = pd.DataFrame();
  62. occupationInfo_header = ['编号', '工作单位', '单位性质', '单位地址', '单位电话']
  63. occupationInfo_header1 = ['编号', '职业', '行业', '职务', '职称', '进入本单位年份', '信息更新日期']
  64. dfMap["occupationDf"] = ({"df": occupationDf, "nextDf": None});
  65. # allHeaders.append(occupationInfo_header1);
  66. allHeaders.append(occupationInfo_header);
  67. # 上次查询记录
  68. preQueryRcd_header0 = ['上一次查询记录']
  69. allHeaders.append(preQueryRcd_header0);
  70. # 查询记录概要
  71. # queryInfoBriefDf = pd.DataFrame();
  72. # queryInfoBrief_header0 = ['最近1个月内的查询机构数', '最近1个月内的查询次数', '最近2年内的查询次数']
  73. # queryInfoBrief_header1 = ['贷款审批', '信用卡审批', '贷款审批', '信用卡\n审批', '本人查询', '贷后管理', '担保资格\n审查', '特约商户\n实名审查']
  74. # dfMap["queryInfoBriefDf"] = ({"df": queryInfoBriefDf, "nextDf": None});
  75. # allHeaders.append(queryInfoBrief_header0);
  76. # allHeaders.append(queryInfoBrief_header1);
  77. # 信贷交易信息提示
  78. loanTradeInfoDf = pd.DataFrame();
  79. loanTradeInfo_header = ['业务类型', '账户数', '首笔业务发放月份'];
  80. dfMap["loanTradeInfoDf"] = ({"df": loanTradeInfoDf, "nextDf": None});
  81. allHeaders.append(loanTradeInfo_header)
  82. # 信贷交易违约信息概要
  83. # 被追偿信息汇总 资产处置和垫款业务
  84. recoveryInfoSumDf = pd.DataFrame();
  85. recoveryInfoSumDf_header = ['业务种类', '账户数', '余额'];
  86. dfMap["recoveryInfoSumDf"] = ({"df": recoveryInfoSumDf, "nextDf": None});
  87. allHeaders.append(recoveryInfoSumDf_header)
  88. # 呆账信息汇总
  89. badDebtsInfoSumDf = pd.DataFrame();
  90. badDebtsInfoSumDf_header = ['账户数', '余额']; # 被追偿信息汇总
  91. dfMap["badDebtsInfoSumDf"] = ({"df": badDebtsInfoSumDf, "nextDf": None});
  92. allHeaders.append(badDebtsInfoSumDf_header)
  93. # 逾期透资信息汇总
  94. overdueInfoSumDf = pd.DataFrame();
  95. overdueInfoSumDf_header = ['账户类型', '账户数', '月份数', '单月最高逾期/透支总额', '最长逾期/透支月数']
  96. dfMap["overdueInfoSumDf"] = ({"df": overdueInfoSumDf, "nextDf": None});
  97. allHeaders.append(overdueInfoSumDf_header)
  98. # 非循环贷账户信息汇总
  99. loanAccountInfoSumDf = pd.DataFrame();
  100. loanAccountInfoSumDf_header0 = ['非循环贷账户信息汇总']
  101. loanAccountInfoSumDf_header1 = ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款']
  102. dfMap["loanAccountInfoSumDf"] = ({"df": loanAccountInfoSumDf, "nextDf": None});
  103. allHeaders.append(loanAccountInfoSumDf_header0)
  104. allHeaders.append(loanAccountInfoSumDf_header1)
  105. # 循环额度下分账户信息汇总
  106. cycleCreditAccountInfoSumDf = pd.DataFrame();
  107. cycleCreditAccountInfoSumDf_header0 = ['循环额度下分账户信息汇总']
  108. cycleCreditAccountInfoSumDf_header1 = ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款'],
  109. dfMap["cycleCreditAccountInfoSumDf"] = ({"df": cycleCreditAccountInfoSumDf, "nextDf": None});
  110. allHeaders.append(cycleCreditAccountInfoSumDf_header0)
  111. allHeaders.append(cycleCreditAccountInfoSumDf_header1)
  112. # 循环贷账户信息汇总
  113. cycleLoanAccountInfoSumDf = pd.DataFrame();
  114. cycleLoanAccountInfoSumDf_header0 = ['循环贷账户信息汇总']
  115. cycleLoanAccountInfoSumDf_header1 = ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款']
  116. dfMap["cycleLoanAccountInfoSumDf"] = ({"df": cycleLoanAccountInfoSumDf, "nextDf": None});
  117. allHeaders.append(cycleLoanAccountInfoSumDf_header0)
  118. allHeaders.append(cycleLoanAccountInfoSumDf_header1)
  119. # 贷记卡账户信息汇总
  120. creditCardInfoSumDf = pd.DataFrame();
  121. creditCardInfoSumDf_header0 = ['贷记卡账户信息汇总']
  122. creditCardInfoSumDf_header1 = ['发卡机构数', '账户数', '授信总额', '单家机构最高\n授信额', '单家机构最低\n授信额', '已用额度', '最近6个月平\n均使用额度']
  123. dfMap["creditCardInfoSumDf"] = ({"df": creditCardInfoSumDf, "nextDf": None});
  124. allHeaders.append(creditCardInfoSumDf_header0)
  125. allHeaders.append(creditCardInfoSumDf_header1)
  126. # 准贷记卡账户信息汇总
  127. creditCardInfoSumDfZ = pd.DataFrame();
  128. creditCardInfoSumDfZ_header0 = ['准贷记卡账户信息汇总']#'准贷记卡账户信息汇总'
  129. creditCardInfoSumDfZ_header1 = ['发卡机构数', '账户数', '授信总额', '单家机构最高\n授信额', '单家机构最低\n授信额', '透支余额', '最近6个月平\n均透支余额']
  130. dfMap["creditCardInfoSumDfZ"] = ({"df": creditCardInfoSumDfZ, "nextDf": None});
  131. allHeaders.append(creditCardInfoSumDfZ_header0)
  132. allHeaders.append(creditCardInfoSumDfZ_header1)
  133. #公共信息概要
  134. publicInfoBriefDf = pd.DataFrame();
  135. publicInfoBriefDf_header0 = ['公共信息汇总']
  136. dfMap["publicInfoBriefDf"] = ({"df": publicInfoBriefDf, "nextDf": None});
  137. allHeaders.append(publicInfoBriefDf_header0)
  138. #查询记录汇总
  139. queryRecordSumDf_header0=['最近1个月内的查询机构数', '最近1个月内的查询次数', '最近2年内的查询次数']
  140. queryRecordSumDf = pd.DataFrame();
  141. dfMap["queryRecordSumDf"] = ({"df": queryRecordSumDf, "nextDf": None});
  142. allHeaders.append(queryRecordSumDf_header0)
  143. # 非循环贷账户,循环额度下分账户
  144. # 循环贷账户
  145. loan_header = ['管理机构', '账户标识', '开立日期', '到期日期', '借款金额', '账户币种']
  146. loanDfs = [];
  147. dfMap["loanDfs"] = ({"dfs": loanDfs, "nextDf": []});
  148. allHeaders.append(loan_header)
  149. # 贷记卡账户
  150. creditCard_header = ['发卡机构', '账户标识', '开立日期', '账户授信额度', '共享授信额度', '币种', '业务种类', '担保方式']
  151. creditCardDfs = [];
  152. dfMap["creditCardDfs"] = ({"dfs": creditCardDfs, "nextDf": []});
  153. allHeaders.append(creditCard_header)
  154. # 准备贷记卡账户
  155. creditCardZ_header = ['发卡机构', '账户标识', '开立日期', '账户授信额度', '共享授信额度', '币种', '担保方式']
  156. creditCardDfsZ = [];
  157. dfMap["creditCardDfsZ"] = ({"dfs": creditCardDfsZ, "nextDf": []});
  158. allHeaders.append(creditCardZ_header)
  159. #
  160. # 相关还款责任信息汇总 未使用到
  161. # 信贷交易信息明细
  162. # 被追偿信息 未使用到
  163. recoveryInfoDfs_header = ['管理机构','业务种类','债权接收日期','债权金额','债权转移时的还款状态']
  164. recoveryInfoDfs = [];
  165. dfMap["recoveryInfoDfs"] = ({"dfs": recoveryInfoDfs, "nextDf": []});
  166. allHeaders.append(recoveryInfoDfs_header)
  167. # 公共信息明细
  168. # 强制执行记录
  169. forceExecRcdDfs_header = ['编号', '执行法院', '执行案由', '立案日期', '结案方式']
  170. forceExecRcdDfs = [];
  171. dfMap["forceExecRcdDfs"] = ({"dfs": forceExecRcdDfs, "nextDf": []});
  172. allHeaders.append(forceExecRcdDfs_header)
  173. # 查询记录
  174. queryRecordDetailDf_header = ['编号', '查询日期', '查询机构', '查询原因']
  175. dfMap["queryRecordDetailDf"] = ({"df": pd.DataFrame(), "nextDf": []});
  176. allHeaders.append(queryRecordDetailDf_header)
  177. #住房公积金参缴记录
  178. housingFundRcdDfs_header =['参缴地', '参缴日期', '初缴月份', '缴至月份', '缴费状态', '月缴存额', '个人缴存比例', '单位缴存比例']
  179. housingFundRcdDfs = []
  180. dfMap["housingFundRcdDfs"] = ({"dfs": housingFundRcdDfs, "nextDf": []});
  181. allHeaders.append(housingFundRcdDfs_header)
  182. repaymentSumDf_header0=['相关还款责任信息汇总']
  183. dfMap["repaymentSumDf"] = ({"df": pd.DataFrame(), "nextDf": None});
  184. allHeaders.append(repaymentSumDf_header0)
  185. # 处理分页思路
  186. # df估计得放到对象里面,然后存储下一个df,一个对象里包含key
  187. # 然后判断对象的df的完整性,如果不完整代表被分页了,把nextdf合并到当前的df
  188. # 针对可合并的列的场景
  189. # =======
  190. keyList = [] # 存储所有的df的key列表
  191. # pd.Series()
  192. # 检查数据是否带表头
  193. # 应该是每一页开头的一行和每个表头对比一次,确认是不是表头,或者表头有什么共同的规律也可以看下
  194. import timeit
  195. # 定义指标部分======================start
  196. reportTime = ""; # 报告时间
  197. # 被查询者姓名
  198. queryInfoName = "";
  199. queryInfoCardId = "" # 被查询者证件号码
  200. # 定义指标部分======================end
  201. # 被查询信息-基础信息
  202. # 报告时间
  203. # 被查询者姓名
  204. # 被查询者证件号码
  205. # 基础信息
  206. queryInfo = {"reportTime":"","queryInfoCardId":""}
  207. # 身份信息
  208. identity = {}
  209. # 配偶信息
  210. mate = {}
  211. # 信贷交易信息提示-信用提示
  212. loanTradeInfo = {'perHouseLoanAccount': 0, 'perBusHouseLoanAccount': 0, 'otherLoanAccount': 0, 'loanMonthMin': 0,
  213. 'creditCardMonthMin': 0, 'creditAccount': 0, 'creditAccountZ': 0}
  214. # 逾期及违约信息概要
  215. overdueBrief = {}
  216. # 逾期及透资信息汇总
  217. # 贷款逾期账户数 loanOverdueAccount
  218. # 贷款逾期月份数 loanOverdueMonth
  219. # 贷款单月最高逾期总额 loanCurMonthOverdueMaxTotal
  220. # 贷款最长逾期月数 loanMaxOverdueMonth
  221. overdueInfo = {"loanOverdueAccount": "", "loanOverdueMonth": "", "loanCurMonthOverdueMaxTotal": "",
  222. "loanMaxOverdueMonth": "",
  223. "creditCardOverdueAccount": "", "creditCardOverdueMonth": "", "creditCardCurMonthOverdueMaxTotal": "",
  224. "creditCardMaxOverdueMonth": ""}
  225. # 未结清贷款信息汇总
  226. # ['管理机构数', '账户数', '授信总额', '余额', '最近6个月平均应还款']
  227. loanAccountInfoSum = {"mgrOrgCount": 0, "account": 0, "creditTotalAmt": 0, "balance": 0, "last6AvgPayAmt": 0}
  228. # 未销户贷记卡发卡法人机构数
  229. # 未销户贷记卡发卡机构数
  230. # 未销户贷记卡账户数
  231. # 未销户贷记卡授信总额
  232. # 未销户贷记卡单家行最高授信额
  233. # 未销户贷记卡单家行最低授信额
  234. # 未销户贷记卡已用额度
  235. # 未销户贷记卡近6月平均使用额度
  236. # 未结清贷记卡信息汇总
  237. # ['发卡机构数', '账户数', '授信总额', '单家机构最高\n授信额', '单家机构最低\n授信额', '已用额度', '最近6个月平\n均使用额度']
  238. creditCardInfoSum = {"awardOrgCount": 0, "account": 0, "creditTotalAmt": 0, "perMaxCreditTotalAmt": 0,
  239. "perMinCreditTotalAmt": 0, "useAmt": 0, "last6AvgUseAmt": 0}
  240. # 信 贷 审 批 查 询 记 录 明 细
  241. queryRecordDetail = {"last1MonthQueryTimes": 0, "last3MothLoanApproveTimes": 0, "last3MonthQueryTimes": 0,
  242. "lastTimeLoanApproveMonth": 0}
  243. #最近一笔结清贷款的贷款金额 
  244. loanAccountInfo = {"lastSettleLoanAmt": 0}
  245. loanAccountDfs=[];#横向合并
  246. creditCardAccountDfs=[];#贷记卡账户合并
  247. creditCardAccountDfsZ=[];#准贷记卡账户合并
  248. recoveryInfoAccountDfs=[];#被追偿账户合并
  249. housingFundRcdAccountDfs=[];#公积金账户合并
  250. #============================指标定义区 start=============================
  251. #基本信息 拆分
  252. # basicInfoDf = pd.DataFrame(columns=consts.basicInfoHeader, index=[0])
  253. #身份信息
  254. identityInfoIndex = '身份信息'
  255. identityInfoDf = pd.DataFrame(columns=consts.identityInfoHeader,index=[identityInfoIndex])
  256. #配偶信息
  257. mateInfoIndex = '配偶信息'
  258. mateInfoDf = pd.DataFrame(columns=consts.mateInfoHeader,index=[mateInfoIndex])
  259. #居住信息
  260. liveInfoIndex = '居住信息'
  261. liveInfoDf = pd.DataFrame(columns=consts.liveInfoHeader,index=[liveInfoIndex])
  262. #职业信息
  263. occupationInfoIndex = '职业信息'
  264. occupationInfoDf = pd.DataFrame(columns=consts.occupationInfoHeader,index=[occupationInfoIndex])
  265. #信贷交易信息提示
  266. loanTradeInfoIndex = '信贷交易信息提示'
  267. briefInfoDf_loanTradeInfo = pd.DataFrame(columns=consts.briefInfoHeader_loanTradeInfo,index=[loanTradeInfoIndex])
  268. #被追偿信息汇总及呆账信息汇总
  269. recoveryInfoSumIndex = '信贷交易违约信息概要'
  270. briefInfoDf_recoveryInfoSum = pd.DataFrame(columns=consts.briefInfoHeader_recoveryInfo,index=[recoveryInfoSumIndex])
  271. #呆账信息汇总
  272. badDebtsInfoIndex = '呆账信息汇总'
  273. briefInfoDf_badDebtsInfoSum = pd.DataFrame(columns=consts.briefInfoHeader_badDebtsInfoSum,index=[badDebtsInfoIndex])
  274. #逾期(透支)信息汇总
  275. overdueInfoSumIndex='逾期(透支)信息汇总'
  276. briefInfoDf_overdueInfoSum = pd.DataFrame(columns=consts.briefInfoHeader_overdueInfoSum,index=[overdueInfoSumIndex])
  277. #信贷交易授信及负债信息概要
  278. loanTradeCreditInfoIndex='信贷交易授信及负债信息概要'
  279. briefInfoDf_loanTradeCreditInfo = pd.DataFrame(columns=consts.briefInfoHeader_loanTradeCreditInfo,index=[loanTradeCreditInfoIndex]).fillna(0.0)
  280. #公共信息概要
  281. publicInfoBriefIndex = '公共信息概要'
  282. publicInfoBriefDf = pd.DataFrame(columns=consts.publicInfoBriefHeader,index=[publicInfoBriefIndex])
  283. #查询记录汇总
  284. queryRecordSumIndex = '查询记录汇总'
  285. queryRecordSumDf = pd.DataFrame(columns=consts.queryRecordSumHeader,index=[queryRecordSumIndex])
  286. #信贷交易明细-被追偿信息
  287. recoveryInfoIndex='被追偿信息'
  288. creditTradeDetailDf_recoveryInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_recoveryInfo,index=[recoveryInfoIndex])
  289. #信贷交易明细-特殊交易
  290. specialTradeIndex='特殊交易'
  291. creditTradeDetailHeader_specialTrade = pd.DataFrame(columns=consts.creditTradeDetailHeader_specialTrade,index=[specialTradeIndex])
  292. #信贷交易明细
  293. #非循环贷账户
  294. loanInfoIndex='非循环贷账户'
  295. creditTradeDetailDf_loanAccountInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_loanAccountInfo,index=[loanInfoIndex])
  296. #循环额度下分账户
  297. cycleCreditAccountInfoIndex='循环额度下分账户'
  298. creditTradeDetailDf_cycleCreditAccountInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_cycleCreditAccountInfo,index=[cycleCreditAccountInfoIndex])
  299. #循环贷账户
  300. cycleLoanAccountInfoIndex='循环贷账户'
  301. creditTradeDetailDf_cycleLoanAccountInfo = pd.DataFrame(columns=consts.creditTradeDetailHeader_cycleLoanAccountInfo,index=[cycleLoanAccountInfoIndex])
  302. #贷款信息
  303. loanAccountInfoIndex='贷款信息'
  304. loanAccountInfoDf = pd.DataFrame(columns=consts.loanAccountInfoHeader,index=[loanAccountInfoIndex])
  305. #贷记卡信息
  306. creditCardAccountInfoIndex = '贷记卡账户'
  307. creditCardAccountInfoDf = pd.DataFrame(columns=consts.creditCardAccountInfoHeader,index=[creditCardAccountInfoIndex])
  308. #准贷记卡
  309. creditCardAccountInfoIndexZ = '准贷记卡账户'
  310. creditCardAccountInfoDfZ = pd.DataFrame(columns=consts.creditCardAccountInfoHeaderZ,index=[creditCardAccountInfoIndexZ])
  311. useRateIndex = '使用率'
  312. useRateDf = pd.DataFrame(columns=consts.creditTradeDetailHeader_useRate,index=[useRateIndex])
  313. openAccountIndex = '开户数'
  314. openAccountDf = pd.DataFrame(columns=consts.creditTradeDetailHeader_openAccount,index=[openAccountIndex])
  315. payRcdStatusIndex = '24期还款状态'
  316. payRcdStatusDf = pd.DataFrame(columns=consts.creditTradeDetailHeader_payRcdStatus,index=[payRcdStatusIndex])
  317. #查询记录明细指标
  318. queryRecordDetailIndex = '信贷审批查询记录明细'
  319. queryRecordDetailDf = pd.DataFrame(columns=consts.queryRecordDetailHeader,index=[queryRecordDetailIndex])
  320. #住房公积金
  321. housingFundRcdIndex = '住房公积金参缴记录'
  322. housingFundRcdDf = pd.DataFrame(columns=consts.housingFundRcdHeader,index=[housingFundRcdIndex])
  323. #============================指标定义区 end=============================
  324. # 解析被查询信息指标
  325. def parseQueryInfo(dfObj):
  326. df = dfObj["df"];
  327. reportTime = df.loc[0, :][3]
  328. reportTime = reportTime.split(":")[1]
  329. reportTime = reportTime.replace(".", "-"); # 报告时间
  330. queryInfo["reportTime"] = reportTime
  331. row = df.loc[2, :]
  332. queryInfo["queryInfoName"] = row[0]; # 被查询者姓名
  333. # basicInfoDf.loc[0, '姓名'] = row[0]
  334. queryInfo["queryInfoCardId"] = row[2].replace("\n", ""); # 被查询者证件号码
  335. # basicInfoDf.loc[0, '身份证'] = row[2].replace("\n", "")
  336. # 婚姻状况
  337. # 学历
  338. # 单位电话
  339. # 住宅电话
  340. # 通讯地址
  341. def parseIdentity(dfObj):
  342. df = dfObj["df"];
  343. if not df.empty:
  344. row1 = df.loc[1, :].dropna().reset_index(drop=True)
  345. # identity["marital"] = row1[3] # 婚姻状况
  346. # identity["education"] = row1[4] # 学历
  347. # identity["commAddress"] = row1[9].replace("\n", ""); # 通讯地址
  348. identityInfoDf.loc[identityInfoIndex, '性别'] = row1[0]
  349. identityInfoDf.loc[identityInfoIndex, '出生日期'] = dfParser.formatDate(row1[1])[0:7]
  350. identityInfoDf.loc[identityInfoIndex, '国籍'] = row1[6]
  351. identityInfoDf.loc[identityInfoIndex, '户籍地址'] = row1[9].replace("\n", "")
  352. identityInfoDf.loc[identityInfoIndex, '婚姻状况'] = row1[2]
  353. identityInfoDf.loc[identityInfoIndex, '学历'] = row1[3].replace("\n", "")
  354. identityInfoDf.loc[identityInfoIndex, '学位'] = row1[4]
  355. identityInfoDf.loc[identityInfoIndex, '通讯地址'] = row1[8].replace("\n", "")
  356. identityInfoDf.loc[identityInfoIndex, '就业状况'] = row1[5]
  357. mobileDf = dfObj["mobileDf"];
  358. identityInfoDf.loc[identityInfoIndex, '历史手机号码数'] = mobileDf.index.size
  359. reportTime = queryInfo["reportTime"]
  360. identityInfoDf.loc[identityInfoIndex, '近3个月手机号码数'] = getLastMonthMobileCount(mobileDf,3,reportTime)
  361. identityInfoDf.loc[identityInfoIndex, '近6个月手机号码数'] = getLastMonthMobileCount(mobileDf, 6,reportTime)
  362. identityInfoDf.loc[identityInfoIndex, '近12个月手机号码数'] = getLastMonthMobileCount(mobileDf, 12,reportTime)
  363. identityInfoDf.loc[identityInfoIndex, '近24个月手机号码数'] = getLastMonthMobileCount(mobileDf, 24,reportTime)
  364. #最近几个月电话号码数
  365. def getLastMonthMobileCount(df, month,reportTime):
  366. # 当前日期
  367. last1MonthDateStr = reportTime
  368. # 最近一个月
  369. lastMonthDate = np.datetime64(last1MonthDateStr, "D") - np.timedelta64(30 * month, 'D')
  370. lastMonthMobileDf = df[df[5] >= str(lastMonthDate)]
  371. return lastMonthMobileDf.shape[0];
  372. # 配偶姓名
  373. # 配偶证件号码
  374. # 配偶工作单位
  375. # 配偶联系电话
  376. def parseMate(dfObj):
  377. df = dfObj["df"];
  378. if not df.empty:
  379. row1 = df.loc[1, :]
  380. mate["mateName"] = row1[0] # 配偶姓名
  381. mate["mateCardId"] = row1[2] # 配偶证件号码
  382. mate["mateWorkCompany"] = row1[3].replace("\n", ""); # 配偶工作单位
  383. mate["mateContactTel"] = row1[4]; # 配偶联系电话
  384. mateInfoDf.loc[mateInfoIndex, '姓名'] = row1[0]
  385. mateInfoDf.loc[mateInfoIndex, '证件号码'] = row1[2]
  386. mateInfoDf.loc[mateInfoIndex, '工作单位'] = row1[3].replace("\n", "");
  387. mateInfoDf.loc[mateInfoIndex, '联系电话'] = row1[4].replace("\n", "");
  388. #解析居住信息
  389. def parseLiveInfo(dfObj):
  390. df = dfObj["df"];
  391. if not df.empty:
  392. row1 = df.loc[1, :]
  393. liveInfoDf.loc[liveInfoIndex, '居住地址'] = row1[1]
  394. liveInfoDf.loc[liveInfoIndex, '住宅电话'] = row1[2]
  395. liveInfoDf.loc[liveInfoIndex, '历史居住地址个数'] = df.index.size-1;
  396. curDate = np.datetime64(time.strftime("%Y-%m-%d"));
  397. last3year = str(curDate)[0:4]
  398. last3yearDate = str(int(last3year)-3)+str(curDate)[4:10]
  399. lastLiveDf = df[df[4]>=last3yearDate];
  400. liveInfoDf.loc[liveInfoIndex, '最近3年内居住地址个数'] = lastLiveDf.index.size-1;
  401. houseIndex = df[df[3]=='自置'].index.size>0
  402. if (houseIndex):
  403. houseStr = '是'
  404. else:
  405. houseStr= '否'
  406. liveInfoDf.loc[liveInfoIndex, '当前居住状况-是否具有自有住房'] = houseStr;
  407. liveInfoDf.loc[liveInfoIndex, '居住状况'] = row1[3]
  408. liveInfoDf.loc[liveInfoIndex, '信息更新日期'] = row1[4]
  409. #解析职业信息
  410. def parseOccupationInfoDf(dfObj):
  411. df = dfObj["df"];
  412. if not df.empty:
  413. occIndex1 = 0#判断职业从哪行开始
  414. for i in range(0,df.index.size):
  415. if df.loc[i,:].dropna().tolist()==occupationInfo_header1:
  416. occIndex1=i;
  417. break;
  418. occDf = df[1:occIndex1].reset_index(drop=True)#工作单位
  419. occDfNew = pd.DataFrame()
  420. occDf1New = pd.DataFrame()
  421. #删除为none的列 合并的bug TODO
  422. for i in range(0,occDf.index.size):
  423. occDfNew = occDfNew.append([pd.DataFrame(occDf.iloc[i].dropna().reset_index(drop=True)).T],ignore_index=True)
  424. occDf1 = df[occIndex1+1:df.index.size].reset_index(drop=True) #职业
  425. for i in range(0,occDf1.index.size):
  426. occDf1New = occDf1New.append([pd.DataFrame(occDf1.iloc[i].dropna().reset_index(drop=True)).T], ignore_index=True)
  427. occDf = pd.concat([occDfNew, occDf1New], axis=1, ignore_index=True)#合并df
  428. row = occDf.loc[0, :].dropna()#取最新
  429. occupationInfoDf.loc[occupationInfoIndex, '工作单位'] = row[1]
  430. last3yearDate = utils.getLastMonthDate(queryInfo['reportTime'],12*3)
  431. occDf = utils.replaceDateColIdx(occDf,occDf.columns.size-1)
  432. dateIndex = occDf.columns.size-1;#日期列
  433. last3yearOccDf = occDf[occDf[dateIndex]>=last3yearDate]
  434. occupationInfoDf.loc[occupationInfoIndex, '最近3年内工作单位数'] = last3yearOccDf.index.size;
  435. occupationInfoDf.loc[occupationInfoIndex, '单位电话'] = row[4];
  436. reportTime = queryInfo['reportTime']
  437. try:
  438. minDateIndex = np.argmin(occDf[dateIndex]);
  439. maxDateIndex = np.argmax(occDf[dateIndex]);
  440. rowYearMin = occDf.loc[minDateIndex, :].dropna()
  441. rowYearMax = occDf.loc[maxDateIndex, :].dropna()
  442. if rowYearMin[10]!="--":
  443. occupationInfoDf.loc[occupationInfoIndex, '最早进入本单位年份距报告日期时长'] = int(str(np.datetime64(reportTime, "Y")))-int(rowYearMin[10])
  444. if rowYearMax[10]!="--":
  445. occupationInfoDf.loc[occupationInfoIndex, '最新进入本单位年份距报告日期时长'] = int(str(np.datetime64(reportTime, "Y")))-int(rowYearMax[10])
  446. except:
  447. logger.error("最早进入本单位年份距报告日期时长解析异常")
  448. row0 = occDf.loc[0,:].dropna().reset_index(drop=True)#最新
  449. occupationInfoDf.loc[occupationInfoIndex, '单位性质'] =row0[2]
  450. occupationInfoDf.loc[occupationInfoIndex, '单位地址'] = row0[3].replace("\n","")
  451. occupationInfoDf.loc[occupationInfoIndex, '职业'] = row0[6]
  452. occupationInfoDf.loc[occupationInfoIndex, '行业'] = row0[7]
  453. occupationInfoDf.loc[occupationInfoIndex, '职务'] = row0[8]
  454. occupationInfoDf.loc[occupationInfoIndex, '职称'] = row0[9]
  455. occupationInfoDf.loc[occupationInfoIndex, '进入本单位年份'] = row0[10]
  456. occupationInfoDf.loc[occupationInfoIndex, '信息更新日期'] = row0[11]
  457. occupationInfoDf.loc[occupationInfoIndex, '历史工作单位数'] = occDf1.index.size
  458. # 日期相减离当前时间月份
  459. # 贷款账龄(月数)=当前日期(2020-04-01)-最小月份的1日(2019.2->2019-12-01)=4
  460. # def difMonth(dateStr):
  461. # return int(int(str(np.datetime64(time.strftime("%Y-%m-%d")) -
  462. # np.datetime64(dateStr.replace('.', '-'), "D")).split(" ")[0]) / 30);
  463. # 信贷交易明细汇总
  464. def parseLoanTradeInfo(dfObj):
  465. df = dfObj["df"];
  466. # row1 = df.loc[1, :]
  467. if not df.empty:
  468. loanMonthDf = df[1: 4]
  469. loanMonthDf = loanMonthDf.reset_index(drop=True)
  470. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '个人住房贷款账户数'] = utils.toInt(loanMonthDf.loc[0, :][2])
  471. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex,'个人商用房贷款(包括商住两用)账户数']=utils.toInt(loanMonthDf.loc[1, :][2])
  472. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '其他类贷款账户数'] = utils.toInt(loanMonthDf.loc[2, :][2])
  473. creditCardDf = df[4: 6];
  474. creditCardDf = creditCardDf.reset_index(drop=True)
  475. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '贷记卡账户数'] = utils.toInt(creditCardDf.loc[0, :][2])
  476. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '准贷记卡账户数'] = utils.toInt(creditCardDf.loc[1, :][2])
  477. # 解析呆账信息汇总
  478. def parseBadDebtsInfoSumDf(dfObj):
  479. df = dfObj["df"];
  480. if not df.empty:
  481. row1 = df.loc[2, :]
  482. briefInfoDf_badDebtsInfoSum.loc[badDebtsInfoIndex, '账户数'] = row1[0];
  483. briefInfoDf_badDebtsInfoSum.loc[badDebtsInfoIndex, '余额'] = utils.replaceAmt(row1[1]);
  484. # 解析被追偿信息汇总
  485. def parseRecoveryInfoSum(dfObj):
  486. df = dfObj["df"];
  487. if not df.empty:
  488. row1 = df.loc[2, :]
  489. row2 = df.loc[3, :]
  490. row3 = df.loc[4, :]
  491. overdueBrief["disposalInfoSumAccount"] = row1[1]; # 资产处置信息汇总笔数
  492. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '资产处置业务账户数'] = row1[1];
  493. overdueBrief["disposalInfoSumAmt"] = row1[2]; # 资产处置信息汇总余额
  494. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '资产处置业务余额'] = utils.replaceAmt(row1[2]);
  495. overdueBrief["advanceInfoSumAccount"] = row2[1]; # 垫款业务笔数
  496. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '垫款业务账户数'] = row2[1];
  497. overdueBrief["advanceInfoSumAmt"] = row2[2]; # 垫款业务余额
  498. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '垫款业务余额'] = utils.replaceAmt(row2[2]);
  499. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '合计总账户数'] = row3[1];
  500. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '合计总余额'] = utils.replaceAmt(row3[2]);
  501. # 贷款逾期账户数
  502. # 贷款逾期月份数
  503. # 贷款单月最高逾期总额
  504. # 贷款最长逾期月数
  505. def parseOverdueInfoSum(dfObj):
  506. df = dfObj["df"];
  507. if not df.empty:
  508. row2= df.loc[2, :]
  509. row3 = df.loc[3, :]
  510. row4 = df.loc[4, :]
  511. row5 = df.loc[5, :]
  512. row6 = df.loc[6, :]
  513. #这块的数据需要进行出来 TODO
  514. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户账户数'] = utils.toInt(row2[1]);
  515. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户月份数'] = utils.toInt(row2[2]);
  516. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户单月最高逾期总额'] = utils.replaceAmt(row2[3]);
  517. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '非循环贷帐户最长逾期月数'] = utils.toInt(row2[4]);
  518. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户账户数'] = utils.toInt(row3[1]);
  519. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户月份数'] = utils.toInt(row3[2]);
  520. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户单月最高逾期总额'] = utils.replaceAmt(row3[3]);
  521. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环额度下分账户最长逾期月数'] = utils.toInt(row3[4]);
  522. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户账户数'] = utils.toInt(row4[1]);
  523. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户月份数'] = utils.toInt(row4[2]);
  524. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户单月最高逾期总额'] = utils.replaceAmt(row4[3]);
  525. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '循环贷账户最长逾期月数'] = utils.toInt(row4[4]);
  526. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户账户数'] = utils.toInt(row5[1]);
  527. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户月份数'] = utils.toInt(row5[2]);
  528. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户单月逾期总额'] = utils.replaceAmt(row5[3]);
  529. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '贷记卡账户最长逾期月数'] = utils.toInt(row5[4]);
  530. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户账户数'] = utils.toInt(row6[1]);
  531. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户月份数'] = utils.toInt(row6[2]);
  532. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户单月透支总额'] = utils.replaceAmt(row6[3]);
  533. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '准贷记卡账户最长透支月数'] = utils.toInt(row6[4]);
  534. overdueInfoAccountDf = df[df[1] != '--'];
  535. overdueInfoAccountDf = overdueInfoAccountDf[2:7]
  536. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户所有逾期账户最长逾期/透支月数最大值']=np.max(overdueInfoAccountDf[4].astype('int'))
  537. #np.sum(overdueInfoAccountDf[1])
  538. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户所有逾期账户数加总']= np.sum(overdueInfoAccountDf[1].astype('int'))# TODO
  539. # briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户过去5年出现逾期的所有账户数目']=None# TODO
  540. # 未结清贷款法人机构数 从“未结清贷款信息汇总”中直接提取LoanLegalOrgNum
  541. # 未结清贷款机构数 从“未结清贷款信息汇总”中直接提取LoanOrgNum
  542. # 未结清贷款笔数 从“未结清贷款信息汇总”中直接提取CountNum
  543. # 未结清贷款合同总额 从“未结清贷款信息汇总”中直接提取ContractProfits
  544. # 未结清贷款合同余额 从“未结清贷款信息汇总”中直接提取Balance
  545. # 未结清贷款近6月平均应还款 从“未结清贷款信息汇总”中直接提取Last6MothsAvgRepayAmount
  546. # 个人贷款未结清笔数 "从“未结清贷款信息汇总”计算客户符合以下条件的贷款笔数
  547. # 1.贷款类型不为('%个人助学贷款%' ,'%农户贷款%')
  548. # 2.贷款额度>100元
  549. # 3.贷款状态不为“结清”"
  550. # 非循环贷账户信息汇总
  551. def doFilterCalc(dfx):
  552. dfx = dfx.replace('--', 0)
  553. return dfx;
  554. # 科学计数法转换
  555. def replaceAmt(dfx):
  556. return dfx.str.replace(',', '')
  557. # 非循环贷账户信息汇总
  558. def parseLoanAccountInfoSum(dfObj):
  559. df = dfObj["df"];
  560. if not df.empty:
  561. loanAccountInfoSumDf = df[2:3];
  562. loanAccountInfoSumDf = doFilterCalc(loanAccountInfoSumDf); # 替换--为0
  563. loanAccountInfoSumDf = loanAccountInfoSumDf.reset_index(drop=True)
  564. row0 = loanAccountInfoSumDf.loc[0,:]
  565. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户管理机构数'] = int(row0[0])
  566. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'] = int(row0[1])
  567. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户授信总额'] = int(utils.replaceAmt(row0[2]))
  568. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户余额'] = int(utils.replaceAmt(row0[3]))
  569. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户6月平均应还款'] = int(utils.replaceAmt(row0[4]))
  570. # 循环额度下分账户
  571. def parseCycleCreditAccountInfoSum(dfObj):
  572. df = dfObj["df"];
  573. if not df.empty:
  574. cycleCreditAccountInfoSumDf = df[2:3];
  575. cycleCreditAccountInfoSumDf = doFilterCalc(cycleCreditAccountInfoSumDf); # 替换--为0
  576. cycleCreditAccountInfoSumDf = cycleCreditAccountInfoSumDf.reset_index(drop=True)
  577. row0 = cycleCreditAccountInfoSumDf.loc[0,:]
  578. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户管理机构数'] = int(row0[0])
  579. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户账户数'] = int(row0[1])
  580. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户授信总额'] = int(utils.replaceAmt(row0[2]))
  581. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户余额'] = int(utils.replaceAmt(row0[3]))
  582. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户6月平均应还款'] = int(utils.replaceAmt(row0[4]))
  583. # 循环贷账户信息
  584. def parseCyleLoanAccountInfoSum(dfObj):
  585. df = dfObj["df"];
  586. if not df.empty:
  587. cycleLoanAccountInfoSumDf = df[2:3];
  588. cycleLoanAccountInfoSumDf = doFilterCalc(cycleLoanAccountInfoSumDf); # 替换--为0
  589. cycleLoanAccountInfoSumDf = cycleLoanAccountInfoSumDf.reset_index(drop=True)
  590. row0 = cycleLoanAccountInfoSumDf.loc[0,:]
  591. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户管理机构数'] = int(row0[0])
  592. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户账户数'] = int(row0[1])
  593. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户授信总额'] = int(utils.replaceAmt(row0[2]))
  594. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户余额'] = int(utils.replaceAmt(row0[3]))
  595. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户6月平均应还款'] = int(utils.replaceAmt(row0[4]))
  596. # 解析贷记卡信息汇总,包含准贷记卡
  597. def parseCreditCardInfoSum(dfObj):
  598. df = dfObj["df"];
  599. if not df.empty:
  600. creditCardInfoSumDf = df[2:3];
  601. creditCardInfoSumDf = doFilterCalc(creditCardInfoSumDf); # 替换--为0
  602. creditCardInfoSumDf = creditCardInfoSumDf.reset_index(drop=True)
  603. row0 = creditCardInfoSumDf.loc[0, :]
  604. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡发卡机构数'] = int(row0[0])
  605. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡账户数'] = int(row0[1])
  606. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡授信总额'] = int(utils.replaceAmt(row0[2]))
  607. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡单家机构最高授信额'] = int(utils.replaceAmt(row0[3]))
  608. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡单家机构最低授信额'] = int(utils.replaceAmt(row0[4]))
  609. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡已用额度'] = int(utils.replaceAmt(row0[5]))
  610. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡最近6个月平均使用额度'] = int(utils.replaceAmt(row0[6]))
  611. # 解析贷记卡信息汇总,包含准贷记卡
  612. def parseCreditCardInfoSumZ(dfObj):
  613. df = dfObj["df"];
  614. if not df.empty:
  615. creditCardInfoSumDfZ = df[2:3];
  616. creditCardInfoSumDfZ = doFilterCalc(creditCardInfoSumDfZ);
  617. creditCardInfoSumDfZ = creditCardInfoSumDfZ.reset_index(drop=True)
  618. row0 = creditCardInfoSumDfZ.loc[0, :]
  619. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡发卡机构数'] = int(row0[0])
  620. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡账户数'] = int(row0[1])
  621. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡授信总额'] = int(utils.replaceAmt(row0[2]))
  622. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡单家机构最高授信额'] = int(utils.replaceAmt(row0[3]))
  623. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡单家机构最低授信额'] = int(utils.replaceAmt(row0[4]))
  624. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡已用额度'] = int(utils.replaceAmt(row0[5]))
  625. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡最近6个月平均使用额度'] = int(utils.replaceAmt(row0[6]))
  626. #相关还款责任
  627. def parseRepaymentSum(dfObj):
  628. df = dfObj["df"];
  629. if not df.empty:
  630. row4 = df.loc[4,:].dropna().reset_index(drop=True)#第4行 为个人
  631. row8 = None
  632. if df.index.size ==9:
  633. row8 = df.loc[8,:].dropna().reset_index(drop=True)#第8行 为企业
  634. perAccountNum = 0;#个人账户数
  635. orgAccountNum = 0; # 企业账户数
  636. totalAccountNum = 0;#总账户数
  637. guaranteeAccountNum = 0;#相关还款责任总账户数-担保责任
  638. otherAccountNum =0;#相关还款责任总账户数-其他
  639. perGuaranteeAmt = 0#个人担保金额及其他
  640. orgGuaranteeAmt = 0#企业担保金额及其他
  641. totalGuaranteeAmt = 0;#总担保金额
  642. guaranteeAmt = 0;#相关还款责任总担保金额
  643. otherPaymentAmt = 0;#其他还款责任金额
  644. perGuaranteeBalance = 0 # 个人担保余额及其他
  645. orgGuaranteeBalance = 0 # 企业担保余额及其他
  646. totalGuaranteeBalance = 0;#总担保余额
  647. guaranteeBalance = 0;#相关还款责任总担保余额
  648. otherPaymentBalance = 0; # 其他还款责任余额
  649. #计算总账户数
  650. if row4[0] !="--":
  651. perAccountNum=perAccountNum+utils.toInt(row4[0])
  652. guaranteeAccountNum = guaranteeAccountNum + utils.toInt(row4[0])#个人担保责任账户数
  653. if row4[3] !="--":
  654. perAccountNum = perAccountNum + utils.toInt(row4[3])#其他
  655. otherAccountNum = otherAccountNum + utils.toInt(row4[3]) # 其他
  656. if row8 != None:
  657. if row8[0] != "--":
  658. orgAccountNum = orgAccountNum + utils.toInt(row8[0])
  659. guaranteeAccountNum = guaranteeAccountNum + utils.toInt(row8[0])#企业担保责任账户数
  660. if row8[3] != "--":
  661. orgAccountNum = orgAccountNum + utils.toInt(row8[3])#其他
  662. otherAccountNum = otherAccountNum + utils.toInt(row8[3]) # 其他
  663. totalAccountNum = perAccountNum+orgAccountNum
  664. #计算担保金额
  665. if row4[1] !="--":
  666. perGuaranteeAmt=perGuaranteeAmt+utils.replaceAmt(row4[1])#担保
  667. guaranteeAmt = guaranteeAmt + utils.replaceAmt(row4[1]) # 担保
  668. if row4[4] !="--":
  669. perGuaranteeAmt = perGuaranteeAmt + utils.replaceAmt(row4[4])#其他
  670. otherPaymentAmt = otherPaymentAmt + utils.replaceAmt(row4[4]) # 其他
  671. if row8 != None:
  672. if row8[1] != "--":
  673. orgGuaranteeAmt = orgGuaranteeAmt + utils.replaceAmt(row8[1])#担保
  674. guaranteeAmt = guaranteeAmt + utils.replaceAmt(row8[1]) # 担保
  675. if row8[4] != "--":
  676. orgGuaranteeAmt = orgGuaranteeAmt + utils.replaceAmt(row8[4])#其他
  677. otherPaymentAmt = otherPaymentAmt + utils.replaceAmt(row8[4]) # 其他
  678. totalGuaranteeAmt = perGuaranteeAmt + orgGuaranteeAmt
  679. # 计算余额
  680. if row4[2] !="--":
  681. perGuaranteeBalance=perGuaranteeBalance+utils.replaceAmt(row4[2])
  682. guaranteeBalance=guaranteeBalance+utils.replaceAmt(row4[2])#个人担保余额
  683. if row4[5] !="--":
  684. perGuaranteeBalance = perGuaranteeBalance + utils.replaceAmt(row4[5])#其他
  685. otherPaymentBalance = otherPaymentBalance + utils.replaceAmt(row4[5]) # 其他
  686. if row8 != None:
  687. if row8[2] != "--":
  688. orgGuaranteeBalance = orgGuaranteeBalance + utils.replaceAmt(row8[2])
  689. guaranteeBalance = guaranteeBalance + utils.replaceAmt(row8[2])#企业担保余额
  690. if row8[5] != "--":
  691. orgGuaranteeBalance = orgGuaranteeBalance + utils.replaceAmt(row8[5])
  692. otherPaymentBalance = otherPaymentBalance + utils.replaceAmt(row8[5]) # 其他
  693. totalGuaranteeBalance = perGuaranteeBalance + orgGuaranteeBalance
  694. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数(担保+其他+个人+企业)'] =totalAccountNum
  695. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额+总还款责任金额(个人+企业)'] =totalGuaranteeAmt
  696. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额+总其他余额(个人+企业)'] =totalGuaranteeBalance
  697. if totalGuaranteeAmt !=0:
  698. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额+总其他余额(个人+企业)/相关还款责任账户总担保金额+总其他金额(个人+企业)'] =\
  699. round(totalGuaranteeBalance / totalGuaranteeAmt, 2)
  700. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任担保总账户数-个人'] =perAccountNum
  701. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-个人'] =perGuaranteeAmt
  702. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-个人'] =perGuaranteeBalance
  703. if perGuaranteeBalance !=0:
  704. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-个人/相关还款责任总担保金额-个人'] = round(perGuaranteeBalance/perGuaranteeBalance,2)
  705. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数-企业'] =orgAccountNum
  706. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-企业'] =orgGuaranteeAmt
  707. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-企业'] =orgGuaranteeBalance
  708. if orgGuaranteeAmt!=0:
  709. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-企业/相关还款责任总担保金额-企业'] = round(orgGuaranteeBalance/orgGuaranteeAmt,2)
  710. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数-担保责任'] =guaranteeAccountNum
  711. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-担保责任'] =guaranteeAmt
  712. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额-担保责任'] =guaranteeBalance
  713. if guaranteeAmt!=0:
  714. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-担保责任/相关还款责任总担保金额-担保责任'] =round(guaranteeBalance/guaranteeAmt,2)
  715. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总账户数-其他'] =otherAccountNum
  716. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保金额-其他'] =otherPaymentAmt
  717. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任总担保余额-其他'] =otherPaymentBalance
  718. if otherPaymentAmt!=0:
  719. briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '相关还款责任账户总担保余额-其他/相关还款责任账户总担保金额-其他'] =round(otherPaymentBalance/otherPaymentAmt,2)
  720. #解析公共信息汇总
  721. def parsePublicInfoBrief(dfObj):
  722. df = dfObj["df"];
  723. if not df.empty:
  724. publicInfoBrief = df[1:6];
  725. publicInfoBrief = publicInfoBrief.reset_index(drop=True)
  726. row0 = publicInfoBrief.loc[0, :]
  727. row1 = publicInfoBrief.loc[1, :]
  728. row2 = publicInfoBrief.loc[2, :]
  729. row3 = publicInfoBrief.loc[3, :]
  730. publicInfoBriefDf.loc[publicInfoBriefIndex, '欠税信息-记录数'] = int(row0[1])
  731. publicInfoBriefDf.loc[publicInfoBriefIndex, '欠税信息-涉及金额'] = int(utils.replaceAmt(row0[2]))
  732. publicInfoBriefDf.loc[publicInfoBriefIndex, '民事判决信息-记录数'] = int(row1[1])
  733. publicInfoBriefDf.loc[publicInfoBriefIndex, '民事判决信息-涉及金额'] = int(utils.replaceAmt(row1[2]))
  734. publicInfoBriefDf.loc[publicInfoBriefIndex, '强制执行信息-记录数'] = int(row2[1])
  735. publicInfoBriefDf.loc[publicInfoBriefIndex, '强制执行信息-涉及金额'] = int(utils.replaceAmt(row2[2]))
  736. publicInfoBriefDf.loc[publicInfoBriefIndex, '行政处罚信息-记录数'] = int(row3[1])
  737. publicInfoBriefDf.loc[publicInfoBriefIndex, '行政处罚信息-涉及金额'] = int(utils.replaceAmt(row3[2]))
  738. #解析查询信息汇总
  739. def parseQueryRecordSum(dfObj):
  740. df = dfObj["df"];
  741. if not df.empty:
  742. queryRecordSumDfTmp = df[2:3];
  743. queryRecordSumDfTmp = queryRecordSumDfTmp.reset_index(drop=True)
  744. row0 = queryRecordSumDfTmp.loc[0, :]
  745. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询机构数-贷款审批'] =int(row0[0])
  746. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询机构数-信用卡审批'] =int(row0[1])
  747. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询次数-贷款审批'] =int(row0[2])
  748. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询次数-信用卡审批'] =int(row0[3])
  749. queryRecordSumDf.loc[queryRecordSumIndex, '近1月内的查询次数-本人查询'] =int(row0[4])
  750. queryRecordSumDf.loc[queryRecordSumIndex, '近2年内的查询次数-贷后管理'] =int(row0[5])
  751. queryRecordSumDf.loc[queryRecordSumIndex, '近2年内的查询次数-担保资格审查'] =int(row0[6])
  752. # 解析查询记录明细
  753. def parseQueryInfoDetail(dfObj):
  754. df = dfObj["df"];
  755. reportTime = queryInfo["reportTime"];
  756. if not df.empty:
  757. df = utils.replaceDateCol(df)
  758. df = df[1:df.index.size] # 去掉表头
  759. queryRecordDetailDf.loc[queryRecordDetailIndex, '近1月查询次数'] =qip.getLastMonthQueryTimes(df, 1, "",reportTime)
  760. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询次数'] =qip.getLastMonthQueryTimes(df, 3, "",reportTime)
  761. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询次数'] =qip.getLastMonthQueryTimes(df, 6, "",reportTime)
  762. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询次数'] =qip.getLastMonthQueryTimes(df, 12, "",reportTime)
  763. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近1个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 1, "", reportTime)
  764. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近3个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 3, "", reportTime)
  765. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近6个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 6, "", reportTime)
  766. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近12个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 12, "", reportTime)
  767. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月查询机构数'] =qip.getLastMonthQueryOrgTimes(df, 24, "", reportTime)
  768. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询次数贷款审批'] =qip.getLastMonthQueryTimes(df, 3, consts.loanApprove, reportTime)
  769. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询次数信用卡审批'] =qip.getLastMonthQueryTimes(df, 3, consts.creditCard, reportTime)
  770. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询次数贷款审批'] =qip.getLastMonthQueryTimes(df, 6, consts.loanApprove, reportTime)
  771. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询次数信用卡审批'] = qip.getLastMonthQueryTimes(df, 6, consts.creditCard, reportTime)
  772. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询次数贷款审批'] = qip.getLastMonthQueryTimes(df, 12, consts.loanApprove, reportTime)
  773. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询次数信用卡审批'] =qip.getLastMonthQueryTimes(df, 12, consts.creditCard, reportTime)
  774. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询机构数贷款审批'] =qip.getLastMonthQueryOrgTimes(df, 3, consts.loanApprove, reportTime)
  775. queryRecordDetailDf.loc[queryRecordDetailIndex, '近3月查询机构数信用卡审批'] =qip.getLastMonthQueryOrgTimes(df, 3, consts.creditCard, reportTime)
  776. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询机构数贷款审批'] =qip.getLastMonthQueryOrgTimes(df, 6, consts.loanApprove, reportTime)
  777. queryRecordDetailDf.loc[queryRecordDetailIndex, '近6月查询机构数信用卡审批'] = qip.getLastMonthQueryOrgTimes(df, 6, consts.creditCard,reportTime)
  778. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询机构数贷款审批'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.loanApprove, reportTime)
  779. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12月查询机构数信用卡审批'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.creditCard,reportTime)
  780. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近6个月担保资格审查查询次数'] = qip.getLastMonthQueryOrgTimes(df, 6, consts.insuranceAprove,reportTime)
  781. queryRecordDetailDf.loc[queryRecordDetailIndex, '近12个月担保资格审查查询次数'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.insuranceAprove,reportTime)
  782. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近6个月贷后管理查询次数'] = qip.getLastMonthQueryOrgTimes(df, 6, consts.loanAfterMgr,reportTime)
  783. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近12个月贷后管理查询次数'] = qip.getLastMonthQueryOrgTimes(df, 12, consts.loanAfterMgr,reportTime)
  784. queryRecordDetailDf.loc[queryRecordDetailIndex, '最后一次查询距离现在的月数贷款审批'] = qip.getLastTimeQueryMonth(df, consts.loanApprove,reportTime)
  785. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月贷后管理查询次数'] = qip.getLastMonthQueryTimes(df, 24, consts.loanAfterMgr, reportTime)
  786. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月贷款审批审批次数'] = qip.getLastMonthQueryTimes(df, 24, consts.loanApprove, reportTime)
  787. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月信用卡审批查询次数'] = qip.getLastMonthQueryTimes(df, 24, consts.creditCard,reportTime)
  788. queryRecordDetailDf.loc[queryRecordDetailIndex, '最近24个月担保资格审查查询次数'] = qip.getLastMonthQueryTimes(df, 24, consts.insuranceAprove,reportTime)
  789. #解析住房公积金
  790. def parseHousingFundRcd(df):
  791. if not df.empty:
  792. lastHousingFundRcdDf = df.sort_values(by=["信息更新日期"] , ascending=(False)).reset_index(drop=True)
  793. lastHousingFundRcdDf = lastHousingFundRcdDf[0:1]#最新
  794. row1 = lastHousingFundRcdDf.loc[0,:].dropna().reset_index(drop=True)
  795. housingFundRcdDf.loc[housingFundRcdIndex, '参缴地'] =row1[1]
  796. housingFundRcdDf.loc[housingFundRcdIndex, '参缴日期'] =row1[2]
  797. housingFundRcdDf.loc[housingFundRcdIndex, '初缴月份'] =row1[3]#初缴日期
  798. housingFundRcdDf.loc[housingFundRcdIndex, '缴至月份'] =row1[4]
  799. housingFundRcdDf.loc[housingFundRcdIndex, '缴费状态'] =row1[5]
  800. housingFundRcdDf.loc[housingFundRcdIndex, '月缴存额'] =row1[6]
  801. housingFundRcdDf.loc[housingFundRcdIndex, '个人存缴比例'] =row1[7]
  802. housingFundRcdDf.loc[housingFundRcdIndex, '单位存缴比例'] =row1[8]
  803. housingFundRcdDf.loc[housingFundRcdIndex, '缴费单位'] =row1[9]#扣缴单位
  804. housingFundRcdDf.loc[housingFundRcdIndex, '信息更新日期'] =row1[10]
  805. reportTime = queryInfo["reportTime"];
  806. lastDateStr = utils.getLastMonthDate(reportTime,12)
  807. avgHousingFundDf = df[df['缴至月份']>=lastDateStr]
  808. housingFundRcdDf.loc[housingFundRcdIndex, '最近1年公积金平均值'] = round(np.mean(avgHousingFundDf['月缴存额']),2)
  809. lastDateStr = utils.getLastMonthDate(reportTime, 12*3)
  810. avgHousingFundDf = df[df['缴至月份'] >= lastDateStr]
  811. housingFundRcdDf.loc[housingFundRcdIndex, '最近3年公积金平均值']= round(np.mean(avgHousingFundDf['月缴存额']),2)
  812. #解析贷款还款记录指标
  813. def parseLoanMergeAndPayRecordDf(df,payRcdDf):
  814. if not df.empty and not payRcdDf.empty:
  815. #正常
  816. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')]
  817. overduePayRcdDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  818. overduePayRcdDf = utils.replacePayRcdStatus(overduePayRcdDf)
  819. #计算当前贷款,为还款记录的最后一期 0529
  820. curOverduePayRcdDf=overduePayRcdDf.sort_values(by=["账户编号", "还款日期"], ascending=(True, False))
  821. curOverduePayRcdDf = curOverduePayRcdDf.groupby(['账户编号']).head(1)
  822. curOverduePayRcdDf = curOverduePayRcdDf[curOverduePayRcdDf['还款状态'] > 0]
  823. #临时保存,不用过滤还款状态为0的
  824. payRcdMaxOverdueDf = overduePayRcdDf;
  825. #所有逾期的记录
  826. # overduePayRcdDf = overduePayRcdDf[overduePayRcdDf['还款状态']>0]
  827. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期账户数'] = curOverduePayRcdDf['账户编号'].unique().size
  828. if normalDf.index.size>0:
  829. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期账户数占比'] = round(loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期账户数']/normalDf.index.size,3)
  830. #存在逾期的贷款账户 非结清的过滤出逾期的账户号
  831. overdueLoanDf = normalDf[normalDf['账户编号'].isin(curOverduePayRcdDf['账户编号'].values)]
  832. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期机构数'] = overdueLoanDf['管理机构'].unique().size
  833. if normalDf['管理机构'].unique().size>0:
  834. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期机构数占比'] = round(loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款逾期机构数'] / normalDf['管理机构'].unique().size,2)
  835. #还款记录按日期排序最近3笔的最大逾期期数
  836. loanAccountInfoDf.loc[loanAccountInfoIndex, '近1月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf,1);
  837. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 3);
  838. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 6);
  839. loanAccountInfoDf.loc[loanAccountInfoIndex, '近9月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 9);
  840. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 12);
  841. loanAccountInfoDf.loc[loanAccountInfoIndex, '近24月贷款的最大逾期期数'] = prp.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 24);
  842. reportTime = queryInfo["reportTime"]
  843. loanAccountInfoDf.loc[loanAccountInfoIndex, '近24月贷款最大逾期距离现在的月数'] = prp.getPayRcdMaxOverdueNumMonth(payRcdMaxOverdueDf,normalDf,reportTime, 24);
  844. payStatus= ["G","D","C","N","M","1","2","3","4","5","6","7"]
  845. # 贷款24期还款记录次数 剔除结清 转出 呆账
  846. payRcdTimesDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  847. payRcdTimesDf = payRcdTimesDf.sort_values(by=["账户编号", "还款日期"], ascending=(True, False))
  848. payRcdTimesDf = payRcdTimesDf.groupby(['账户编号']).head(24)
  849. #从“贷款信息”中提取,剔除“账户状态”为结清、转出、呆账、呆帐后,各账户的还款次数统计“24个月(账户)还款状态”包含"G","D","C","N","M"及数字的个数,MAX(各账户的还款次数)
  850. payRcdTimesDf = payRcdTimesDf[payRcdTimesDf['还款状态'].isin(payStatus)]
  851. payRcdTimes = payRcdTimesDf.groupby(['账户编号'])['还款状态'].count()
  852. loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款24期还款记录次数'] = np.max(payRcdTimes)
  853. #解析信贷交易明细-特殊交易
  854. def parseSpecialTrade(df):
  855. if not df.empty:
  856. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '当前用户发生特殊交易的严重程度'] = np.max(df['严重程度'])#加工的指标
  857. maxChangeMonthIndex = np.argmax(np.abs(df['变更月数']))
  858. meanMonthValue = np.mean(np.abs(df['变更月数']))
  859. row0 = df.loc[maxChangeMonthIndex, :]
  860. settleDf = df[(df['特殊交易类型']=='提前结清') | (df['特殊交易类型']=='提前还款')]
  861. debtDf = df[(df['特殊交易类型'] == '以资抵债')]
  862. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户发生特殊交易变更月数的最大差值'] = row0[3]
  863. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户发生特殊交易变更月数的平均差值'] = round(meanMonthValue,2)
  864. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户特殊交易涉及的发生金额的最大值'] = np.max(df['发生金额'])
  865. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户特殊交易涉及的发生金额的平均值'] = round(np.mean(df['发生金额']),2)
  866. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户所有帐户发生提前还款交易的次数统计'] = settleDf.index.size
  867. creditTradeDetailHeader_specialTrade.loc[specialTradeIndex, '用户所有帐户发生不良特殊交易的次数统计'] = debtDf.index.size;
  868. #信贷交易明细-非循环贷账户
  869. def parseLoanAccountInfo(df):
  870. if not df.empty:
  871. loanAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'])
  872. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')].reset_index(drop=True)
  873. normalDf = normalDf[0:loanAccountNum]#根据非循环贷账户数进行计算进行截取
  874. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '本月应还款(合计)'] = np.sum(normalDf['本月应还款'])
  875. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '本月实还款(合计)'] = np.sum(normalDf['本月实还款'])
  876. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '最近一次还款日期'] = np.max(normalDf['最近一次还款日期'])
  877. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '当前一共逾期期数'] = np.sum(normalDf['当前逾期期数'])
  878. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '当前一共逾期总额'] = np.sum(normalDf['当前逾期总额'])
  879. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期31-60天未还本金(合计)'] = np.sum(normalDf['逾期31-60天未还本金'])
  880. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期61-90天未还本金(合计)'] = np.sum(normalDf['逾期61-90天未还本金'])
  881. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期91-180天未还本金(合计)'] = np.sum(normalDf['逾期91-180天未还本金'])
  882. creditTradeDetailDf_loanAccountInfo.loc[loanInfoIndex, '逾期180天以上未还本金(合计)']= np.sum(normalDf['逾期180天以上未还本金'])
  883. #信贷交易明细-循环额度分账户
  884. def parseCycleCreditAccountInfo(df):
  885. if not df.empty:
  886. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')].reset_index(drop=True)
  887. loanAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'])
  888. cycleCreditAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户账户数'])
  889. normalDf = normalDf[loanAccountNum:(loanAccountNum + cycleCreditAccountNum)]
  890. if not normalDf.empty:
  891. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '本月应还款(合计)'] = np.sum(normalDf['本月应还款'])
  892. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '本月实还款(合计)'] = np.sum(normalDf['本月实还款'])
  893. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '最近一次还款日期'] = np.max(normalDf['最近一次还款日期'])
  894. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '当前一共逾期期数'] = np.sum(normalDf['当前逾期期数'])
  895. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '当前一共逾期总额'] = np.sum(normalDf['当前逾期总额'])
  896. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期31-60天未还本金(合计)'] = np.sum(normalDf['逾期31-60天未还本金'])
  897. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期61-90天未还本金(合计)'] = np.sum(normalDf['逾期61-90天未还本金'])
  898. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期91-180天未还本金(合计)'] = np.sum(normalDf['逾期91-180天未还本金'])
  899. creditTradeDetailDf_cycleCreditAccountInfo.loc[cycleCreditAccountInfoIndex, '逾期180天以上未还本金(合计)']= np.sum(normalDf['逾期180天以上未还本金'])
  900. #信贷交易明细-循环贷账户
  901. def parseCycleLoanAccountInfo(df):
  902. if not df.empty:
  903. normalDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')]
  904. loanAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户账户数'])
  905. cycleCreditAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户账户数'])
  906. cycleAccountNum = int(briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户账户数'])
  907. normalDf = normalDf[(loanAccountNum+cycleCreditAccountNum):normalDf.index.size]
  908. if not normalDf.empty:
  909. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '本月应还款(合计)'] = np.sum(normalDf['本月应还款'])
  910. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '本月实还款(合计)'] = np.sum(normalDf['本月实还款'])
  911. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '最近一次还款日期'] = np.max(normalDf['最近一次还款日期'])
  912. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '当前一共逾期期数'] = np.sum(normalDf['当前逾期期数'])
  913. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '当前一共逾期总额'] = np.sum(normalDf['当前逾期总额'])
  914. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期31-60天未还本金(合计)'] = np.sum(normalDf['逾期31-60天未还本金'])
  915. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期61-90天未还本金(合计)'] = np.sum(normalDf['逾期61-90天未还本金'])
  916. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期91-180天未还本金(合计)'] = np.sum(normalDf['逾期91-180天未还本金'])
  917. creditTradeDetailDf_cycleLoanAccountInfo.loc[cycleLoanAccountInfoIndex, '逾期180天以上未还本金(合计)']= np.sum(normalDf['逾期180天以上未还本金'])
  918. #解析贷款账户信息指标
  919. def parseLoanMergeDf(df):
  920. if not df.empty:
  921. sortDf = df.sort_values(by=["账户关闭日期","借款金额(本金)"] , ascending=(False,False))
  922. sortDf = sortDf[sortDf['账户状态'] == '结清'];
  923. sortDf = sortDf.reset_index(drop=True)
  924. if not sortDf.empty:
  925. row0 = sortDf.loc[0, :]
  926. loanAccountInfo["lastSettleLoanAmt"] = row0['借款金额(本金)']
  927. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近一笔结清贷款的贷款金额'] = row0['借款金额(本金)']
  928. openDate = dfParser.formatDate(row0['开立日期'])
  929. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近一笔结清贷款的发放距今月数'] = utils.difMonthReportTime(openDate,queryInfo["reportTime"])
  930. settleDate = dfParser.formatDate(row0['账户关闭日期'])
  931. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近一笔结清贷款的结清距今月数'] = utils.difMonthReportTime(settleDate,queryInfo["reportTime"])
  932. loanAccountInfoDf.loc[loanAccountInfoIndex, '历史贷款总法人机构数'] = df['管理机构'].unique().size
  933. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前同时在用的贷款机构数'] = df[df['余额(本金)']>0]['管理机构'].unique().size
  934. statusDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出')]
  935. bankDf = statusDf[statusDf['管理机构'].str.contains('银行')]
  936. #没有记录
  937. if statusDf.index.size==0:
  938. isNotBankCust = -1
  939. else:
  940. if bankDf.index.size >0:#有一条以上不为结清,请包含银行
  941. isNotBankCust = 1;
  942. else:
  943. isNotBankCust = 0;
  944. loanAccountInfoDf.loc[loanAccountInfoIndex, '是否有非银行贷款客户'] = isNotBankCust
  945. #最严重的五级分类
  946. # fiveType = ""
  947. # for fiveTypeTmp in consts.fiveType:
  948. # fiveTypeDf = statusDf[statusDf['五级分类']==fiveTypeTmp];
  949. # if not fiveTypeDf.empty:
  950. # fiveType = fiveTypeTmp;
  951. # break;
  952. # loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款五级分类'] = fiveType
  953. #当前贷款LTV
  954. # 从“贷款信息”中提取,剔除“账户状态”为结清及转出,并剔除“账户状态”为呆账且本金余额 = 0
  955. # 的记录后,SUM(本金余额) / SUM(贷款本金)
  956. # 如本金余额为空和贷款本金为0或为空,则当条记录不计算
  957. loanLtvDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['借款金额(本金)']>0) & (df['余额(本金)']!='--')]
  958. badSetDf = loanLtvDf[~((loanLtvDf['账户状态'] == '呆账') & (loanLtvDf['余额(本金)']==0))]
  959. balanceSum = np.sum(badSetDf['余额(本金)'].astype('int'))
  960. loanAmtSum = np.sum(badSetDf['借款金额(本金)'].astype('int'))
  961. if(loanAmtSum !=0):
  962. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款LTV'] = round(np.divide(balanceSum,loanAmtSum),2)
  963. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最高LTV'] = round(np.max(np.divide(badSetDf['余额(本金)'].astype('int'), badSetDf['借款金额(本金)'].astype('int'))),2)
  964. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最低LTV'] = round(np.min(np.divide(badSetDf['余额(本金)'].astype('int'), badSetDf['借款金额(本金)'].astype('int'))), 2)
  965. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款平均LTV'] = round(np.mean(np.divide(badSetDf['余额(本金)'].astype('int'), badSetDf['借款金额(本金)'].astype('int'))), 2)
  966. #['个人住房商业贷款','个人商用房(含商住两用)贷款','个人住房公积金贷款','房'],
  967. houseLtvList = consts.houseLtvList;
  968. # houseLtvDf = badSetDf[badSetDf['业务种类'].isin(houseLtvList)]
  969. # if not houseLtvDf.empty:
  970. # loanAccountInfoDf.loc[loanAccountInfoIndex, '当前房贷LTV'] = round(np.divide(np.sum(houseLtvDf['余额(本金)'].astype('int')),np.sum(houseLtvDf['借款金额(本金)'].astype('int'))), 2)
  971. #['个人住房贷款','个人商用房(包括商住两用)贷款']
  972. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前房贷LTV'] = lip.getCurLtv(badSetDf, houseLtvList)
  973. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款机构数量'] = loanLtvDf['管理机构'].unique().size
  974. cardLtvList = ['个人汽车消费贷款','车']
  975. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前车贷LTV'] = lip.getCurLtv(badSetDf, cardLtvList)
  976. operateLtvList = ['个人经营性贷款']
  977. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前经营贷LTV'] = lip.getCurLtv(badSetDf, operateLtvList)
  978. consumeLtvList = ['其他个人消费贷款']
  979. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前消费贷LTV'] = lip.getCurLtv(badSetDf, consumeLtvList)
  980. bankLtvList = ['商业银行','外资银行','村镇银行','住房储蓄银行','财务公司']
  981. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前银行贷LTV'] = lip.getCurBankLtv(badSetDf, bankLtvList)
  982. bankLtvList = ['消费金融公司','汽车金融公司','信托公司']# TODO
  983. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前消金贷LTV'] = lip.getCurBankLtv(badSetDf, bankLtvList)
  984. smallLoanLtvList = ['小额信贷公司']
  985. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前小贷LTV'] = lip.getCurBankLtv(badSetDf, smallLoanLtvList)
  986. #当前贷款最大逾期期数
  987. # 从“贷款信息”中提取,剔除“账户状态”为结清、转出、呆账、呆帐后,MAX(每笔贷款的当前逾期期数)
  988. loanOverdueLtvDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出') & (df['账户状态'] != '呆账')]
  989. if not loanOverdueLtvDf.empty:
  990. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最大逾期期数'] = np.max(loanOverdueLtvDf['当前逾期期数'])
  991. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最大逾期金额'] = np.max(loanOverdueLtvDf['当前逾期总额'])
  992. loanOverdueLtvDf=loanOverdueLtvDf.reset_index(drop=True)
  993. maxOverdueIndex = np.argmax(loanOverdueLtvDf['当前逾期期数'])
  994. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款最大逾期期数对应的最大逾期金额'] = loanOverdueLtvDf.loc[maxOverdueIndex,:]['当前逾期总额']
  995. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月开户最高贷款本金'] = lip.getLastLoanAmtMax(df,queryInfo["reportTime"],3)#贷款指标加工单独放到一个文件里
  996. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月开户最低贷款本金'] = lip.getLastLoanAmtMin(df, queryInfo["reportTime"], 3)
  997. loanAccountInfoDf.loc[loanAccountInfoIndex, '近3月开户平均贷款本金'] = lip.getLastLoanAmtAvg(df, queryInfo["reportTime"], 3)
  998. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月开户最高贷款本金'] = lip.getLastLoanAmtMax(df, queryInfo["reportTime"], 6)
  999. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月开户最低贷款本金'] = lip.getLastLoanAmtMin(df, queryInfo["reportTime"], 6)
  1000. loanAccountInfoDf.loc[loanAccountInfoIndex, '近6月开户平均贷款本金'] = lip.getLastLoanAmtAvg(df, queryInfo["reportTime"], 6)
  1001. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月开户最高贷款本金'] = lip.getLastLoanAmtMax(df, queryInfo["reportTime"], 12)
  1002. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月开户最低贷款本金'] = lip.getLastLoanAmtMin(df, queryInfo["reportTime"], 12)
  1003. loanAccountInfoDf.loc[loanAccountInfoIndex, '近12月开户平均贷款本金'] = lip.getLastLoanAmtAvg(df, queryInfo["reportTime"], 12)
  1004. lastLoanDf = loanOverdueLtvDf;
  1005. if not lastLoanDf.empty:
  1006. loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款最近一次还款日期距今时长'] = lip.getLastPayDateMinDays(lastLoanDf,queryInfo["reportTime"])
  1007. normalDf = df[(df['账户状态'] == '正常') & (df['当前逾期期数'] == 0)]
  1008. #未结清贷款总账户数:账户状态不等于结清和转出的记录数
  1009. notSettleDf = df[(df['账户状态'] != '结清') & (df['账户状态'] != '转出')]
  1010. if not notSettleDf.empty:
  1011. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户数'] = normalDf.index.size
  1012. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户数占比'] = round(normalDf.index.size/notSettleDf.index.size,2)
  1013. #当前未结清贷款余额总和
  1014. # ltvDf = tmpDf[tmpDf['业务种类'].isin(bizTypeList)]
  1015. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清贷款余额总和'] = np.sum(notSettleDf['余额(本金)'])
  1016. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清贷款余额总和'] = np.sum(notSettleDf['余额(本金)'])
  1017. # 当前未结清住房贷款余额总和
  1018. houseDf = notSettleDf[notSettleDf['业务种类'].isin(houseLtvList)]
  1019. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清住房贷款余额总和'] = np.sum(houseDf['余额(本金)'])
  1020. # 当前未结清汽车贷款余额总和
  1021. cardDf = notSettleDf[notSettleDf['业务种类'].isin(cardLtvList)]
  1022. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清汽车贷款余额总和'] = np.sum(cardDf['余额(本金)'])
  1023. # 当前未结清个人经营性贷款余额总和
  1024. operateLtvDf = notSettleDf[notSettleDf['业务种类'].isin(operateLtvList)]
  1025. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前未结清个人经营性贷款余额总和'] = np.sum(operateLtvDf['余额(本金)'])
  1026. # 当前平均每月贷款余额总和
  1027. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前平均每月贷款余额总和'] = round(np.sum(notSettleDf['余额(本金)'])/12,2)
  1028. #当前正常贷款账户余额
  1029. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户余额'] = np.sum(normalDf['余额(本金)'])
  1030. # "从“贷款信息”中提取,剔除结清、转出,当前正常贷款账户余额/未结清贷款总余额(本金余额加总)
  1031. if np.sum(notSettleDf['余额(本金)']) >0:
  1032. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常贷款账户余额占总余额比'] = round(np.sum(normalDf['余额(本金)'])/np.sum(notSettleDf['余额(本金)']),2)
  1033. settleDf = df[(df['账户状态'] == '结清')]
  1034. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常结清贷款账户数'] = settleDf.index.size
  1035. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前正常结清贷款账户数占比'] = round(settleDf.index.size/df.index.size,2)
  1036. #贷款24期还款记录次数 TODO
  1037. # 最近3个月个人消费贷款发放额度
  1038. loanAccountInfoDf.loc[loanAccountInfoIndex, '贷款本月实还款金额'] = np.sum(loanOverdueLtvDf['本月应还款'])
  1039. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近3个月个人消费贷款发放额度'] = lip.getLastPerConsumeAmt(df,3,queryInfo["reportTime"])
  1040. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近6个月个人消费贷款发放额度'] = lip.getLastPerConsumeAmt(df, 6,queryInfo["reportTime"])
  1041. loanAccountInfoDf.loc[loanAccountInfoIndex, '最近12个月个人消费贷款发放额度'] = lip.getLastPerConsumeAmt(df, 12,queryInfo["reportTime"])
  1042. #未结清贷款平均剩余还款期数
  1043. payPieDf = notSettleDf[notSettleDf['还款期数']!='--']
  1044. if payPieDf.index.size!=0:
  1045. loanAccountInfoDf.loc[loanAccountInfoIndex, '未结清贷款平均剩余还款期数'] = round(np.sum(payPieDf['剩余还款期数'])/payPieDf.index.size,2)
  1046. # 当前贷款本月应还金额总和
  1047. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款本月应还金额总和'] = np.sum(notSettleDf['本月应还款'])
  1048. # 当前贷款本月实还金额总额
  1049. loanAccountInfoDf.loc[loanAccountInfoIndex, '当前贷款本月实还金额总额'] = np.sum(notSettleDf['本月实还款'])
  1050. #解析贷记卡账户信息指标
  1051. def parseCreditCardMergeDf(df):
  1052. if not df.empty:
  1053. # 历史信用卡总法人机构数
  1054. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex,'历史信用卡总法人机构数'] = df['发卡机构'].unique().size
  1055. # creditCardUseDf = df[df['已用额度']>0];
  1056. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex,'当前同时在用的信用卡机构数'] = creditCardUseDf['发卡机构'].unique().size
  1057. #统一排除
  1058. creditDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '未激活') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1059. totalAmtDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '未激活') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1060. #大额专项分期额度(合计)
  1061. # 已用分期金额(合计)
  1062. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '大额专项分期额度(合计)'] = np.sum(creditDf['大额专项分期额度'])
  1063. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '已用分期金额(合计)'] = np.sum(creditDf['已用分期金额'])
  1064. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex,'贷记卡账户当前总额度'] = cip.getMaxCreditAmt(creditDf)
  1065. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近新发放的3张贷记卡平均额度'] = cip.getAvgCreditAmt(creditDf)
  1066. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡额度使用率超过90%的机构数占比'] = cip.getUseRate(creditDf,df,0.9)
  1067. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡额度使用率超过100%的机构数占比'] = cip.getUseRate(creditDf, totalAmtDf, 1)
  1068. # 从“贷记卡信息”中提取,计算授信额度时剔除销户,计算已用额度时剔除呆账、呆帐、销户后,SUM(各账户已用额度) / SUM(各账户授信额度)
  1069. useCreditDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1070. totalCreditDf = df[(df['币种'] == '人民币元') & (df['账户状态'] != '销户')]
  1071. totalCreditAmt = np.sum(totalCreditDf['账户授信额度'])
  1072. if totalCreditAmt != 0:#授信额度不能为0
  1073. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡账户当前总额度使用率'] = round(np.sum(useCreditDf['已用额度'])/np.sum(totalCreditDf['账户授信额度']),2)
  1074. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡账户最高使用额度总的使用率'] = round(np.sum(useCreditDf['最大使用额']) / np.sum(totalCreditDf['账户授信额度']), 2)
  1075. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡账户近6月平均额度总的使用率'] = round(np.sum(useCreditDf['最近6个月平均使用额度']) / np.sum(totalCreditDf['账户授信额度']), 2)
  1076. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡最大逾期期数'] = np.max(creditDf['当前逾期期数'])#用于计算
  1077. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡最大逾期金额'] = np.max(creditDf['当前逾期总额'])
  1078. if not creditDf.empty:
  1079. creditDf = creditDf.reset_index(drop=True)
  1080. maxOverdueIndex = np.argmax(creditDf['当前逾期期数'])
  1081. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡最大逾期期数对应的最大逾期金额'] = creditDf.loc[maxOverdueIndex,:]['当前逾期总额']
  1082. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月开卡最高额度'] = cip.getLastMonthMaxCreditAmt(df,queryInfo["reportTime"],3)
  1083. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月开卡最低额度'] = cip.getLastMonthMinCreditAmt(df, queryInfo["reportTime"], 3)
  1084. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月开卡平均额度'] = cip.getLastMonthAvgCreditAmt(df, queryInfo["reportTime"], 3)
  1085. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月开卡最高额度'] = cip.getLastMonthMaxCreditAmt(df, queryInfo["reportTime"], 6)
  1086. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月开卡最低额度'] = cip.getLastMonthMinCreditAmt(df, queryInfo["reportTime"], 6)
  1087. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月开卡平均额度'] = cip.getLastMonthAvgCreditAmt(df, queryInfo["reportTime"], 6)
  1088. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月开卡最高额度'] = cip.getLastMonthMaxCreditAmt(df, queryInfo["reportTime"], 12)
  1089. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月开卡最低额度'] = cip.getLastMonthMinCreditAmt(df, queryInfo["reportTime"], 12)
  1090. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月开卡平均额度'] = cip.getLastMonthAvgCreditAmt(df, queryInfo["reportTime"], 12)
  1091. if not creditDf.empty:
  1092. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡最近一次还款日期距今时长'] = cip.getLastPayDateMinDays(creditDf,queryInfo["reportTime"])
  1093. paySo = np.sum(creditDf['本月应还款'])
  1094. if(paySo)!=0:
  1095. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡还款比例'] = round(np.sum(creditDf['本月实还款'])/np.sum(creditDf['本月应还款']),2)
  1096. creditDfTmp = creditDf[creditDf['本月应还款']>0]
  1097. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡最高还款比例'] = round(np.max(np.divide(creditDfTmp['本月实还款'] , creditDfTmp['本月应还款'])), 2)
  1098. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡最低还款比例'] = round(np.min(np.divide(creditDfTmp['本月实还款'] , creditDfTmp['本月应还款'])), 2)
  1099. normalDf = df[(df['币种'] == '人民币元') & (df['账户状态'] == '正常') & (df['当前逾期期数']==0)];
  1100. notCloseDf = df[(df['账户状态'] != '销户')]
  1101. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡账户数'] = normalDf.index.size
  1102. if not notCloseDf.empty and not normalDf.empty:
  1103. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡账户数占比'] = round(normalDf.index.size/notCloseDf.index.size,2)
  1104. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡已用额度'] = np.sum(normalDf['已用额度'])
  1105. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数'] = normalDf[normalDf['已用额度']>0].index.size
  1106. if not creditDf.empty:
  1107. creditUseAmt = np.sum(creditDf['已用额度'])
  1108. if creditUseAmt!=0:
  1109. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常贷记卡账户余额占总余额比'] = round(np.sum(normalDf['已用额度']) / np.sum(creditDf['已用额度']), 2)
  1110. if notCloseDf.empty:
  1111. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数占比'] = -99
  1112. else:
  1113. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数占比'] = \
  1114. round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前正常且有余额的贷记卡账户数']/notCloseDf.index.size,3)
  1115. #当前正常贷记卡账户余额占总余额比
  1116. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡本月实还金额总和'] = np.sum(creditDf['本月实还款'])
  1117. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡本月应还金额总和'] = np.sum(creditDf['本月应还款'])
  1118. maxAmtDf = df[(df['币种'] == '人民币元')]
  1119. if not maxAmtDf.empty:
  1120. maxAmtDf = maxAmtDf.reset_index(drop=True)
  1121. maxAmtIndex = np.argmax(maxAmtDf['账户授信额度'])
  1122. maxOpenDate = maxAmtDf.loc[maxAmtIndex,:]['开立日期'];
  1123. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '额度最高的人民币贷记卡开卡距今月份数'] = utils.difMonthReportTime(maxOpenDate,queryInfo["reportTime"]);
  1124. # 名下贷记卡数量-状态正常
  1125. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态正常'] = df[(df['账户状态'] != '销户')].index.size
  1126. # 名下贷记卡数量-状态未激活
  1127. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态未激活'] = df[(df['账户状态'] == '未激活')].index.size
  1128. # 名下贷记卡数量-状态异常--异常包含(2-冻结,3-止付,5-呆帐,10-其他)
  1129. abnormalList = ['冻结','止付','呆帐','其他']
  1130. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态异常'] = df[(df['账户状态'].isin(abnormalList))].index.size
  1131. # 名下贷记卡比例-状态正常
  1132. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡比例-状态正常'] = round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态正常'] / df.index.size,2)
  1133. # 名下贷记卡比例-状态未激活
  1134. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡比例-状态未激活'] =round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态未激活'] / df.index.size,2)
  1135. # 名下贷记卡比例-状态异常
  1136. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡比例-状态异常'] = round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '名下贷记卡数量-状态异常'] / df.index.size,2)
  1137. #解析准贷记卡账户信息指标
  1138. def parseCreditCardMergeDfZ(df,payRcd):
  1139. if not df.empty:
  1140. overdueCreditCardRcdDf = payRcd[payRcd['账户编号'].isin(df['账户编号'].values)];
  1141. overdueCreditCardRcdDf = utils.replacePayRcdStatusOverdue(overdueCreditCardRcdDf)
  1142. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '本月应还款(合计)'] = np.nansum(df['透支余额'])
  1143. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '本月实还款(合计)'] = np.nansum(df['本月实还款'])
  1144. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '最近一次还款日期'] = np.nanmax(df['最近一次还款日期'])
  1145. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前一共透支期数'] = cip.getCurOverdueNum(overdueCreditCardRcdDf);
  1146. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前一共透支总额'] = np.nansum(df['透支余额'])
  1147. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '透支180天以上未支付余额(合计)'] = np.nansum(df['透支180天以上未付余额'])
  1148. creditDf = df[(df['账户状态'] != '未激活') & (df['账户状态'] != '销户')]
  1149. if not creditDf.empty:
  1150. totalAmt = np.nansum(creditDf['账户授信额度'])
  1151. creditAmt = np.nansum(creditDf['透支余额'])
  1152. if totalAmt !=0:
  1153. #从“贷记卡信息”中提取,剔除未激活、销户后,所有账户透支金额/所有账户账户授信额度。
  1154. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '全部准贷记卡账户当前总额度使用率']=round(creditAmt/totalAmt,2)
  1155. #从“贷记卡信息”中提取,剔除未激活、销户后,MAX(单账户最高透支金额/单账户授信额度)
  1156. creditMaxDf = creditDf[creditDf['账户授信额度']>0]
  1157. if not creditMaxDf.empty:
  1158. creditMaxDf = creditMaxDf.fillna(0.0)
  1159. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '准贷记卡账户最高使用额度总的使用率'] = round(np.max(np.divide(creditMaxDf['最大透支余额'],creditMaxDf['账户授信额度'])),2)
  1160. creditMaxDf = creditDf[creditDf['最大透支余额'] > 0]
  1161. if not creditMaxDf.empty:
  1162. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡最大透支金额'] = np.max(creditMaxDf['最大透支余额'])
  1163. #从“贷记卡信息”中提取,剔除未激活、销户后,当前透支准贷记卡账户数/总准贷记卡账户数,透支账户判断:透支余额不为0的账户
  1164. creditDfTmp = creditDf[creditDf['透支余额']>0]
  1165. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡透支账户数占比'] = round(creditDfTmp.index.size / creditDf.index.size,2)
  1166. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡本月应还金额总和'] = np.nansum(df['透支余额'])
  1167. creditCardAccountInfoDfZ.loc[creditCardAccountInfoIndexZ, '当前准贷记卡本月实还金额总和'] = np.nansum(df['本月实还款'])
  1168. #解析使用率 TODO 使用汇总计算还是使用明细计算
  1169. def parseUseRate():
  1170. # useRateDf.loc[useRateIndex, '贷记卡账户使用率(已用额度/授信总额)']
  1171. # 从“信贷交易授信及负债信息概要”中“非循环贷账户信息汇总”、“循环额度下分账户信息汇总”、“循环贷账户信息汇总”、“贷记卡账户信息汇总”和“准贷记卡账户信息汇总”里提取,SUM(
  1172. # 所有“余额”、“已用额度”和“透支余额”) / SUM(所有“授信总额”和“授信额度”)
  1173. loanUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户余额']
  1174. cycleCreditUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户余额']
  1175. cycleUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户余额']
  1176. creditUseAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡已用额度']
  1177. creditAmtUseZ = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡已用额度']
  1178. loanTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '非循环贷账户授信总额']
  1179. cycleCreditTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环额度下分账户授信总额']
  1180. cycleTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '循环贷账户授信总额']
  1181. creditTotalAmt = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '贷记卡授信总额']
  1182. creditAmtTotalZ = briefInfoDf_loanTradeCreditInfo.loc[loanTradeCreditInfoIndex, '准贷记卡授信总额']
  1183. # if str(loanUseAmt)=="nan":
  1184. # loanUseAmt = 0;
  1185. # if str(cycleCreditUseAmt) == "nan":
  1186. # loanUseAmt = 0;
  1187. # if str(cycleCreditUseAmt) == "nan":
  1188. # loanUseAmt = 0;
  1189. useAmt = loanUseAmt+cycleCreditUseAmt+cycleUseAmt+creditUseAmt+creditAmtUseZ
  1190. totalAmt = loanTotalAmt+cycleCreditTotalAmt+cycleTotalAmt+creditTotalAmt+creditAmtTotalZ
  1191. if totalAmt !=0:
  1192. useRateDf.loc[useRateIndex, '全账户使用率(已用额度/授信总额)'] = round(useAmt / totalAmt,2)
  1193. if loanTotalAmt!=0:
  1194. useRateDf.loc[useRateIndex, '非循环贷账户使用率(已用额度/授信总额)'] = round(loanUseAmt / loanTotalAmt,2)
  1195. if cycleCreditTotalAmt !=0:
  1196. useRateDf.loc[useRateIndex, '循环额度下分账户使用率(已用额度/授信总额)'] = round(cycleCreditTotalAmt / cycleCreditTotalAmt,2)
  1197. if cycleTotalAmt !=0:
  1198. useRateDf.loc[useRateIndex, '循环贷账户使用率(已用额度/授信总额)'] = round(cycleUseAmt / cycleTotalAmt,2)
  1199. if creditTotalAmt !=0:
  1200. useRateDf.loc[useRateIndex, '贷记卡账户使用率(已用额度/授信总额)'] = round(creditUseAmt / creditTotalAmt,2)
  1201. if creditAmtTotalZ !=0:
  1202. useRateDf.loc[useRateIndex, '准贷记卡账户使用率(已用额度/授信总额)'] = round(creditAmtUseZ / creditAmtTotalZ,2)
  1203. #解析开户数
  1204. def parseOpenAccount(loanDf,creditCardDf,creditCardDfZ,recoveryInfoMergeDf,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ):
  1205. reportTime = queryInfo["reportTime"];
  1206. openAccountDf.loc[openAccountIndex, '近3个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,3)+cip.getOpenAccount(creditCardDf,reportTime,3)+cip.getOpenAccount(creditCardDfZ,reportTime,3)
  1207. openAccountDf.loc[openAccountIndex, '近6个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,6)+cip.getOpenAccount(creditCardDf,reportTime,6)+cip.getOpenAccount(creditCardDfZ,reportTime,6)
  1208. openAccountDf.loc[openAccountIndex, '近9个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,9)+cip.getOpenAccount(creditCardDf,reportTime,9)+cip.getOpenAccount(creditCardDfZ,reportTime,9)
  1209. openAccountDf.loc[openAccountIndex, '近12个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,12)+cip.getOpenAccount(creditCardDf,reportTime,12)+cip.getOpenAccount(creditCardDfZ,reportTime,12)
  1210. openAccountDf.loc[openAccountIndex, '近24个月全账户开户数'] = cip.getOpenAccount(loanDf,reportTime,24)+cip.getOpenAccount(creditCardDf,reportTime,24)+cip.getOpenAccount(creditCardDfZ,reportTime,24)
  1211. openAccountDf.loc[openAccountIndex, '近3个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,3,consts.bankList)
  1212. openAccountDf.loc[openAccountIndex, '近6个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,6,consts.bankList)
  1213. openAccountDf.loc[openAccountIndex, '近9个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,9,consts.bankList)
  1214. openAccountDf.loc[openAccountIndex, '近12个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,12,consts.bankList)
  1215. openAccountDf.loc[openAccountIndex, '近24个月消费金融类账户开户数'] = lip.getOpenAccount(loanDf,reportTime,24,consts.bankList)
  1216. openAccountDf.loc[openAccountIndex, '近3个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,3,"")
  1217. openAccountDf.loc[openAccountIndex, '近6个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,6,"")
  1218. openAccountDf.loc[openAccountIndex, '近9个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,9,"")
  1219. openAccountDf.loc[openAccountIndex, '近12个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,12,"")
  1220. openAccountDf.loc[openAccountIndex, '近24个月贷款账户开户数'] = lip.getOpenAccount(loanDf,reportTime,24,"")
  1221. openAccountDf.loc[openAccountIndex, '近3个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,3)
  1222. openAccountDf.loc[openAccountIndex, '近6个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,6)
  1223. openAccountDf.loc[openAccountIndex, '近9个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,9)
  1224. openAccountDf.loc[openAccountIndex, '近12个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,12)
  1225. openAccountDf.loc[openAccountIndex, '近24个月贷记卡账户开户数'] = cip.getOpenAccount(creditCardDf,reportTime,24)
  1226. openAccountDf.loc[openAccountIndex, '近3个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,3)
  1227. openAccountDf.loc[openAccountIndex, '近6个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,6)
  1228. openAccountDf.loc[openAccountIndex, '近9个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,9)
  1229. openAccountDf.loc[openAccountIndex, '近12个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,12)
  1230. openAccountDf.loc[openAccountIndex, '近24个月准贷记卡账户开户数'] = cip.getOpenAccount(creditCardDfZ,reportTime,24)
  1231. #从“信贷交易信息明细”中“非循环贷账户”、“循环额度下分账户”、“循环贷账户”、“贷记卡账户”和“准贷记卡账户”里提取,5年里账户还款状态出现“1、2、3、4、5、6、7、D、Z、G、B”的账户数/所有账户数
  1232. overdueLoanPayRcdDf = loanPayRecordMergeDf[loanPayRecordMergeDf['账户编号'].isin(loanDf['账户编号'].values)]
  1233. overdueLoanPayRcdDf = utils.replacePayRcdStatusOverdue(overdueLoanPayRcdDf)
  1234. overdueLoanPayRcdDf = overdueLoanPayRcdDf[overdueLoanPayRcdDf['还款状态'] > 0]
  1235. overdueCreditPayRcdDf = creditCardPayRecordMergeDf[creditCardPayRecordMergeDf['账户编号'].isin(creditCardDf['账户编号'].values)]
  1236. overdueCreditPayRcdDf = utils.replacePayRcdStatusOverdue(overdueCreditPayRcdDf)
  1237. overdueCreditPayRcdDf = overdueCreditPayRcdDf[overdueCreditPayRcdDf['还款状态'] > 0]
  1238. overdueCreditPayRcdDfZ = creditCardPayRecordMergeDfZ[creditCardPayRecordMergeDfZ['账户编号'].isin(creditCardDfZ['账户编号'].values)]
  1239. overdueCreditPayRcdDfZ = utils.replacePayRcdStatusOverdue(overdueCreditPayRcdDfZ)
  1240. overdueCreditPayRcdDfZ = overdueCreditPayRcdDfZ[overdueCreditPayRcdDfZ['还款状态'] > 0]
  1241. loanAccountNum = loanPayRecordMergeDf['账户编号'].unique().size
  1242. creditAccountNum = creditCardPayRecordMergeDf['账户编号'].unique().size
  1243. creditAccountNumZ = creditCardPayRecordMergeDfZ['账户编号'].unique().size
  1244. overdueLoanNum = overdueLoanPayRcdDf['账户编号'].unique().size
  1245. overdueCreditNum = overdueCreditPayRcdDf['账户编号'].unique().size
  1246. overdueCreditNumZ = overdueCreditPayRcdDfZ['账户编号'].unique().size
  1247. if (loanAccountNum+creditAccountNum+creditAccountNumZ) >0:
  1248. openAccountDf.loc[openAccountIndex, '有过逾期记录的账户/全账户数'] = round((overdueLoanNum+overdueCreditNum+overdueCreditNumZ)/(loanAccountNum+creditAccountNum+creditAccountNumZ),2)
  1249. otherPerLoanDf = loanDf[loanDf['业务种类'].isin(consts.bankList)]
  1250. otherPerLoanNum = otherPerLoanDf.index.size;
  1251. overdueOtherPerLoanNum = otherPerLoanDf[otherPerLoanDf['账户编号'].isin(overdueLoanPayRcdDf['账户编号'].values)].index.size;
  1252. if otherPerLoanNum!=0:
  1253. openAccountDf.loc[openAccountIndex, '有过逾期记录的消费金融类账户/全消费金融类账户数'] = round(overdueOtherPerLoanNum/otherPerLoanNum,2)
  1254. if loanAccountNum!=0:
  1255. openAccountDf.loc[openAccountIndex, '有过逾期记录的贷款账户/全贷款账户数'] = round(overdueLoanNum/loanAccountNum,2)
  1256. if creditAccountNum!=0:
  1257. openAccountDf.loc[openAccountIndex, '有过逾期记录的贷记卡账户/全贷记卡账户数'] = round(overdueCreditNum/creditAccountNum,2)
  1258. if creditAccountNumZ!=0:
  1259. openAccountDf.loc[openAccountIndex, '有过透支记录的准贷记卡账户/全准贷记卡账户数']= round(overdueCreditNumZ/creditAccountNumZ,2)
  1260. # 0525新增
  1261. pledgeLoanDf = loanDf[loanDf['担保方式'] =='抵押']
  1262. pledgeCreditCardDf = creditCardDf[creditCardDf['担保方式'] == '抵押']
  1263. pledgeCreditCardDfZ = creditCardDfZ[creditCardDfZ['担保方式'] == '抵押']
  1264. isPledge = "否"
  1265. if pledgeLoanDf.index.size+pledgeCreditCardDf.index.size+pledgeCreditCardDfZ.index.size >0:
  1266. isPledge = "是"
  1267. creditLoanDf = loanDf[loanDf['担保方式'] == '信用/免担保']
  1268. creditCreditCardDf = creditCardDf[creditCardDf['担保方式'] == '信用/免担保']
  1269. creditCreditCardDfZ = creditCardDfZ[creditCardDfZ['担保方式'] == '信用/免担保']
  1270. isCredit = 0
  1271. if creditLoanDf.index.size + creditCreditCardDf.index.size + creditCreditCardDfZ.index.size > 0:
  1272. isCredit = creditLoanDf.index.size + creditCreditCardDf.index.size + creditCreditCardDfZ.index.size
  1273. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '是否存在担保方式为抵押的贷款'] = isPledge
  1274. briefInfoDf_loanTradeInfo.loc[loanTradeInfoIndex, '担保方式为信用的贷款数量'] = isCredit
  1275. #解析24期还款状态指标
  1276. def parsePayRcdStatus(loanMergeDf, creditCardMergeDf, creditCardMergeDfZ,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ):
  1277. #creditCardPayRecordMergeDf
  1278. # 去掉外币
  1279. creditCardMergeDf = creditCardMergeDf[creditCardMergeDf['币种']=='人民币元']
  1280. creditCardPayRecordMergeDf = creditCardPayRecordMergeDf[creditCardPayRecordMergeDf['账户编号'].isin(creditCardMergeDf['账户编号'].values)]
  1281. reportTime = queryInfo["reportTime"];
  1282. reportTime = str(np.datetime64(reportTime, "M"))+"-02"#06-02,统计24期还款状态报告期,按每月的2号,避免chu'xian
  1283. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近3月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,3)
  1284. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近6月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,6)
  1285. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,12)
  1286. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,24)
  1287. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近6月逾期期数大于或等于“2”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,6)
  1288. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或等于“2”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,12)
  1289. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“2”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,24)
  1290. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近6月逾期期数大于或等于“3”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,6)
  1291. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或等于“3”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,12)
  1292. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“3”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,24)
  1293. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近12月逾期期数大于或大等于“4”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,12)
  1294. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24月逾期期数大于或等于“4”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,24)
  1295. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近3月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,3)
  1296. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近6月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,6)
  1297. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,12)
  1298. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“1”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,24)
  1299. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近6月逾期期数大于或等于“2”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,6)
  1300. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“2”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,12)
  1301. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“2”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,24)
  1302. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近6月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,6)
  1303. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,12)
  1304. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,24)
  1305. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近12月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,12)
  1306. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,24)
  1307. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近6月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,6)
  1308. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近12月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,12)
  1309. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近24月逾期期数大于或等于“3”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,24)
  1310. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近6月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,6)
  1311. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近12月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,12)
  1312. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近24月逾期期数大于或等于“4”的次数'] = cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,24)
  1313. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近3月逾期期数大于或等于“1”的次数'] = prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,3)\
  1314. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,3)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,3)
  1315. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近6月逾期期数大于或等于“1”的次数'] = \
  1316. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,6)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,6)\
  1317. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,6)
  1318. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“1”的次数'] = \
  1319. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,12)\
  1320. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,12)
  1321. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“1”的次数'] = \
  1322. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,1,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,1,24)\
  1323. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,1,24)
  1324. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近6月逾期期数大于或等于“2”的次数'] = \
  1325. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,6)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,6)\
  1326. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,2,6)
  1327. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“2”的次数'] = \
  1328. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,12)\
  1329. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,2,12)
  1330. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“2”的次数'] = \
  1331. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,2,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,2,24)\
  1332. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,2,24)
  1333. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近6月逾期期数大于或等于“3”的次数'] = \
  1334. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,6)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,6)\
  1335. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,6)
  1336. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“3”的次数'] = \
  1337. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,12)\
  1338. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,12)
  1339. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“3”的次数'] = \
  1340. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,3,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,3,24)\
  1341. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,3,24)
  1342. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近12月逾期期数大于或等于“4”的次数'] = \
  1343. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,12)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,12)\
  1344. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,12)
  1345. payRcdStatusDf.loc[payRcdStatusIndex, '全账户近24月逾期期数大于或等于“4”的次数'] = \
  1346. prp.getLoanOverdueTimes(loanPayRecordMergeDf,reportTime,4,24)+cip.getLoanOverdueTimes(creditCardPayRecordMergeDf,reportTime,4,24)\
  1347. +cip.getLoanOverdueTimes(creditCardPayRecordMergeDfZ,reportTime,4,24)
  1348. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24个月是否出现"G"'] = prp.isExistsInd(loanPayRecordMergeDf,reportTime,"G",24)
  1349. payRcdStatusDf.loc[payRcdStatusIndex, '贷记卡账户近24个月是否出现"G"'] = prp.isExistsInd(creditCardPayRecordMergeDf,reportTime,"G",24)
  1350. payRcdStatusDf.loc[payRcdStatusIndex, '准贷记卡账户近24个月是否出现"G"'] = prp.isExistsInd(creditCardPayRecordMergeDfZ,reportTime,"G",24)
  1351. payRcdStatusDf.loc[payRcdStatusIndex, '贷款账户近24个月是否出现"Z"'] = prp.isExistsInd(loanPayRecordMergeDf,reportTime,"Z",24)
  1352. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷款账户过去24个月存在逾期的账户数目'] = prp.getLoanOverdueCount(loanPayRecordMergeDf,reportTime,24)
  1353. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷款账户过去24个月状态正常账户数目'] = prp.getLoanNormalCount(loanPayRecordMergeDf,reportTime,24)
  1354. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷记卡账户过去24个月存在逾期的账户数目'] = prp.getLoanOverdueCount(creditCardPayRecordMergeDf,reportTime,24)
  1355. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有贷记卡账户过去24个月状态正常的账户数目'] = prp.getLoanNormalCount(creditCardPayRecordMergeDf,reportTime,24)
  1356. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有准贷记卡账户过去24个月存在逾期的账户数目'] = prp.getLoanOverdueCount(creditCardPayRecordMergeDfZ,reportTime,24)
  1357. payRcdStatusDf.loc[payRcdStatusIndex, '用户所有准贷记卡账户过去24个月状态正常的账户数目'] = prp.getLoanNormalCount(creditCardPayRecordMergeDfZ,reportTime,24)
  1358. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去3个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,3)
  1359. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去6个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,6)
  1360. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去12个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,12)
  1361. payRcdStatusDf.loc[payRcdStatusIndex, '用户过去24个月最大逾期期数'] = prp.getPayRcdMaxOverdueNumAllAccout(loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ,reportTime,24)
  1362. #概要信息里的字段,从还款状态计算
  1363. briefInfoDf_overdueInfoSum.loc[overdueInfoSumIndex, '该用户过去5年出现逾期的所有账户数目'] = \
  1364. prp.getLoanOverdueCount(loanPayRecordMergeDf,reportTime,24*5)+prp.getLoanOverdueCount(creditCardPayRecordMergeDf,reportTime,24*5)\
  1365. +prp.getLoanOverdueCount(creditCardPayRecordMergeDfZ,reportTime,24*5)
  1366. #解析贷款还款记录指标
  1367. def parseCreditCardMergeAndPayRecordDf(df,payRcdDf):
  1368. if not df.empty and not payRcdDf.empty:
  1369. # 正常
  1370. normalDf = df[(df['账户状态'] != '未激活') & (df['账户状态'] != '销户') & (df['账户状态'] != '呆账')]
  1371. if not normalDf.empty:
  1372. overduePayRcdDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  1373. overduePayRcdDf = utils.replacePayRcdStatus(overduePayRcdDf)
  1374. # 计算当前贷款,为还款记录的最后一期 0529
  1375. curOverduePayRcdDf = overduePayRcdDf.sort_values(by=["账户编号", "还款日期"], ascending=(True, False))
  1376. curOverduePayRcdDf = curOverduePayRcdDf.groupby(['账户编号']).head(1)
  1377. curOverduePayRcdDf = curOverduePayRcdDf[curOverduePayRcdDf['还款状态'] > 0]
  1378. # 临时保存,不用过滤还款状态为0的
  1379. payRcdMaxOverdueDf = overduePayRcdDf;
  1380. # overduePayRcdDf = overduePayRcdDf[overduePayRcdDf['还款状态'] > 0]
  1381. # creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期账户数'] = curOverduePayRcdDf['账户编号'].unique().size
  1382. #从“贷记卡信息”中提取,剔除“账户状态”为未激活、销户、呆账、呆帐后,“当前信用卡逾期账户数”/未销户贷记卡账户数(剔除“账户状态”为未激活、销户、呆账、呆帐后记录条数)
  1383. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期账户数占比'] = round(curOverduePayRcdDf['账户编号'].unique().size / normalDf.index.size, 2)
  1384. #从“贷记卡信息”中提取,剔除“账户状态”为未激活、销户、呆账、呆帐后,对(当前信用卡逾期账户数)按“开户机构代码”去重统计账户状态为逾期,按按“开户机构代码”去重后的记录条数
  1385. overdueCreditCardDf = normalDf[normalDf['账户编号'].isin(curOverduePayRcdDf['账户编号'].values)]
  1386. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期机构数'] = overdueCreditCardDf['发卡机构'].unique().size
  1387. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期机构数占比'] = round(creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '当前贷记卡逾期机构数'] / normalDf['发卡机构'].unique().size, 2)
  1388. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近3月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 3);
  1389. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近6月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 6);
  1390. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近9月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 9);
  1391. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近12月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 12);
  1392. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近24月贷记卡最大逾期期数'] = cip.getPayRcdMaxOverdueNum(payRcdMaxOverdueDf, 24);
  1393. reportTime = queryInfo["reportTime"]
  1394. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '近24月贷记卡最大逾期距离现在的月数'] = cip.getPayRcdMaxOverdueNumMonth(payRcdMaxOverdueDf,normalDf,reportTime, 24);
  1395. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近3个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,3);
  1396. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近6个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,6);
  1397. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近9个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,9);
  1398. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近12个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,12);
  1399. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '最近24个月贷记卡最大连续逾期月份数'] = cip.getContinuousOverdueMonth(payRcdMaxOverdueDf,normalDf,24);
  1400. payRcdTimesDf = payRcdDf[payRcdDf['账户编号'].isin(normalDf['账户编号'].values)]
  1401. payRcdTimesDf = payRcdTimesDf.sort_values(by=["账户编号", "还款日期"], ascending=(True, False))
  1402. payRcdTimesDf = payRcdTimesDf.groupby(['账户编号']).head(24)
  1403. payStatus = ["G", "D", "C", "N", "M", "1", "2", "3", "4", "5", "6", "7"]
  1404. payRcdTimesDf = payRcdTimesDf[payRcdTimesDf['还款状态'].isin(payStatus)]
  1405. payRcdTimes = payRcdTimesDf.groupby(['账户编号'])['还款状态'].count()
  1406. #从“贷记卡信息”中提取,剔除未激活、销户、呆账、呆帐后,各账户的还款次数统计“24个月(账户)还款状态”包含"G","D","C","N","M"及数字的个数
  1407. creditCardAccountInfoDf.loc[creditCardAccountInfoIndex, '贷记卡24期还款记录次数'] = np.max(payRcdTimes)
  1408. # 解析被追偿信息汇总
  1409. def parseRecoveryInfoMergeDf(df):
  1410. if not df.empty:
  1411. recoveryMaxPayDf = df[df['债权转移时的还款状态'] !='--']
  1412. recoveryStatusCs = df[df['账户状态'] == '催收']
  1413. if not recoveryMaxPayDf.empty:
  1414. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '债权转移时的最大还款状态'] = np.max(recoveryMaxPayDf['债权转移时的还款状态']);
  1415. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '债权转移时属于催收状态的账户数'] = recoveryStatusCs.index.size;
  1416. briefInfoDf_recoveryInfoSum.loc[recoveryInfoSumIndex, '债权转移时属于催收状态的账户数/被追偿信息总数'] = round(recoveryStatusCs.index.size/df.index.size,2);
  1417. #creditTradeDetailDf_recoveryInfo
  1418. # 被追偿账户总数
  1419. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex,'被追偿账户总数'] = df.index.size;
  1420. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '被追偿业务种类'] = df['业务种类'].unique().size;
  1421. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '最新一笔被追偿债券接收时间'] = np.max(df['债权接收日期']);
  1422. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '总债权金额'] = np.max(df['债权金额']);
  1423. creditTradeDetailDf_recoveryInfo.loc[recoveryInfoIndex, '债权转移时的最大还款状态'] = np.max(recoveryMaxPayDf['债权转移时的还款状态']);
  1424. def main(pdf_path):
  1425. # 解析pdf开始
  1426. fileName = os.path.basename(pdf_path)
  1427. print(fileName)
  1428. with pdfplumber.open(pdf_path) as pdf:
  1429. for p in range(0, len(pdf.pages)):
  1430. page = pdf.pages[p]
  1431. # first_page = pdf.pages[1]
  1432. # if p == 3:
  1433. # print(3)
  1434. tables = page.extract_tables();
  1435. for i in range(0, len(tables)):
  1436. table = tables[i]
  1437. df = pd.DataFrame(table);
  1438. # if p==12:
  1439. # logger.info(p)
  1440. if len(keyList) > 1 and i == 0: # 判断是否被分页了
  1441. if not utils.checkHeader(df, allHeaders):
  1442. key = keyList[-1];
  1443. dfObj = dfMap[key]
  1444. # dfObj["nextDf"]=df;
  1445. # 贷款信息 贷记卡信息 强制执行记录
  1446. if key == "loanDfs" or key == "creditCardDfs" or key == "creditCardDfsZ" or key == "forceExecRcdDfs" or key == 'recoveryInfoDfs' or key == "housingFundRcdDfs": # 属于列表
  1447. lastDfObj = dfObj["dfs"][-1];
  1448. lastDfObj["isByPage"] = str(p + 1);
  1449. if len(dfObj["dfs"][-1]["df"].columns) == len(df.columns): # 列数相同
  1450. lastDfObj["df"] = pd.concat([lastDfObj["df"], df], axis=0,ignore_index=True); # 去最后一个进行合并
  1451. # print("key-" + key + "-page-" + str(p + 1) + "-" + "###列数相同####-被分页")
  1452. else:
  1453. # print("key-" + key + "-page-" + str(p + 1) + "-" + "列数不同-被分页")
  1454. lastDfObj["df"] = pd.concat([lastDfObj["df"], df], axis=0, ignore_index=True);
  1455. else: # 查询记录明细 为单个列表
  1456. dfObj["isByPage"] = str(p + 1);
  1457. logger.info(fileName+"#"+key)
  1458. if len(dfObj["df"].columns) == len(df.columns):
  1459. # print("key-" + key + "-page-" + str(p + 1) + "-" + "###列数相同####-被分页")
  1460. dfObj["df"] = pd.concat([dfObj["df"], df], axis=0, ignore_index=True)
  1461. else:
  1462. # print("key-" + key + "-page-" + str(p + 1) + "-" + "列数不同-被分页")
  1463. dfObj["df"] = pd.concat([dfObj["df"], df], axis=0, ignore_index=True)
  1464. # dfObj["nextDf"] = df;
  1465. # 如果列数相等合并df
  1466. continue;
  1467. headerList0 = df.loc[0, :].tolist() # 第0行为表头
  1468. headerList0 = list(filter(None, headerList0))
  1469. headerList1 = []
  1470. if df.index.size>1:
  1471. headerList1 = df.loc[1, :].tolist() # 第1行为表头
  1472. headerList1 = list(filter(None, headerList1))
  1473. if headerList1 == queryInfoDf_header: # 被查询信息 第二行为数据
  1474. queryInfoDf = df;
  1475. dfKey = "queryInfoDf"
  1476. dfMap[dfKey]["df"] = df;
  1477. keyList.append(dfKey);
  1478. elif headerList0 == identity_header: # 身份信息
  1479. identityDf = df[:2] # 截取前2行
  1480. addressDf = df.loc[2:4,:] # 截取3到4行的第一和6
  1481. addressDf = addressDf.reset_index(drop=True)
  1482. mobileDf = utils.replaceDateColIdx(df[5:df.index.size], 5)
  1483. identityDf = pd.concat([identityDf, addressDf], axis=1, ignore_index=True) # 横向合并
  1484. dfKey = "identityDf"
  1485. dfMap[dfKey]["df"] = identityDf;
  1486. keyList.append(dfKey);
  1487. # 组装电话号码df
  1488. dfMap[dfKey]["mobileDf"] = mobileDf
  1489. elif headerList0 == mateDf_header: # 配偶信息
  1490. mateDf = df;
  1491. dfKey = "mateDf"
  1492. dfMap[dfKey]["df"] = df;
  1493. keyList.append(dfKey);
  1494. elif headerList0 == liveInfoDf_header: # 居住信息
  1495. mateDf = df;
  1496. dfKey = "liveInfoDf"
  1497. dfMap[dfKey]["df"] = df;
  1498. keyList.append(dfKey);
  1499. elif headerList0 == occupationInfo_header: # 职业信息 可能存在分页
  1500. occupationDf = df;
  1501. dfKey = "occupationDf"
  1502. dfMap[dfKey]["df"] = df;
  1503. keyList.append(dfKey);
  1504. # elif headerList0 == queryInfoBrief_header0 and headerList1 == queryInfoBrief_header1: # 查询信息概要 第二行为数据
  1505. # queryInfoBriefDf = df;
  1506. # dfKey = "queryInfoBriefDf"
  1507. # dfMap[dfKey]["df"] = df;
  1508. # keyList.append(dfKey);
  1509. elif headerList0 == loanTradeInfo_header: # 信贷交易信息
  1510. loanTradeInfoDf = df;
  1511. dfKey = "loanTradeInfoDf";
  1512. dfMap[dfKey]["df"] = df;
  1513. keyList.append(dfKey);
  1514. elif headerList1 == recoveryInfoSumDf_header: # 被追偿信息汇总
  1515. recoveryInfoSumDf = df;
  1516. dfKey = "recoveryInfoSumDf";
  1517. dfMap[dfKey]["df"] = df;
  1518. keyList.append(dfKey);
  1519. elif headerList1 == badDebtsInfoSumDf_header: # 呆账信息
  1520. badDebtsInfoSumDf = df;
  1521. dfKey = "badDebtsInfoSumDf";
  1522. dfMap[dfKey]["df"] = df;
  1523. keyList.append(dfKey);
  1524. elif headerList1 == overdueInfoSumDf_header: # 逾期透资信息汇总
  1525. overdueInfoSumDf = df;
  1526. dfKey = "overdueInfoSumDf";
  1527. dfMap[dfKey]["df"] = df;
  1528. keyList.append(dfKey);
  1529. elif headerList0 == loanAccountInfoSumDf_header0 and headerList1 == loanAccountInfoSumDf_header1: # 非循环贷账户信息汇总
  1530. loanAccountInfoSumDf = df;
  1531. dfKey = "loanAccountInfoSumDf";
  1532. dfMap[dfKey]["df"] = df;
  1533. keyList.append(dfKey);
  1534. elif headerList0 == creditCardInfoSumDf_header0 and headerList1 == creditCardInfoSumDf_header1: # 贷记卡信息汇总
  1535. creditCardInfoSumDf = df;
  1536. dfKey = "creditCardInfoSumDf";
  1537. dfMap[dfKey]["df"] = df;
  1538. keyList.append(dfKey);
  1539. elif headerList0 == creditCardInfoSumDfZ_header0 and headerList1 == creditCardInfoSumDfZ_header1: # 准贷记卡信息汇总 目前没有数据
  1540. dfKey = "creditCardInfoSumDfZ";
  1541. dfMap[dfKey]["df"] = df;
  1542. keyList.append(dfKey);
  1543. elif headerList0 == repaymentSumDf_header0:#相关还款责任汇总
  1544. dfKey = "repaymentSumDf";
  1545. dfMap[dfKey]["df"] = df;
  1546. keyList.append(dfKey);
  1547. elif headerList0 == publicInfoBriefDf_header0: #公共信息概要
  1548. dfKey = "publicInfoBriefDf";
  1549. dfMap[dfKey]["df"] = df;
  1550. keyList.append(dfKey);
  1551. elif headerList0 == queryRecordSumDf_header0:#查询记录汇总
  1552. dfKey = "queryRecordSumDf";
  1553. dfMap[dfKey]["df"] = df;
  1554. keyList.append(dfKey);
  1555. elif headerList0 == loan_header: # 贷款账户 包括循环贷,非循环贷 循环额度下分账户
  1556. dfKey = "loanDfs";
  1557. dfMap[dfKey]["dfs"].append({"df": df});
  1558. keyList.append(dfKey);
  1559. elif headerList0 == creditCard_header: # 贷记卡账户
  1560. dfKey = "creditCardDfs";
  1561. dfMap[dfKey]["dfs"].append({"df": df});
  1562. keyList.append(dfKey);
  1563. elif headerList0 == creditCardZ_header: # 准贷记卡账户 还不能和贷记卡合并
  1564. dfKey = "creditCardDfsZ";
  1565. dfMap[dfKey]["dfs"].append({"df": df});
  1566. keyList.append(dfKey);
  1567. elif headerList0 == queryRecordDetailDf_header: # 查询记录明细
  1568. dfKey = "queryRecordDetailDf";
  1569. dfMap[dfKey]["df"] = df;
  1570. keyList.append(dfKey);
  1571. elif headerList0 == housingFundRcdDfs_header: # 查询记录明细
  1572. dfKey = "housingFundRcdDfs";
  1573. dfMap[dfKey]["dfs"].append({"df": df});
  1574. keyList.append(dfKey);
  1575. elif headerList0 == forceExecRcdDfs_header: # 强制执行记录
  1576. dfKey = "forceExecRcdDfs";
  1577. dfMap[dfKey]["dfs"].append({"df": df});
  1578. keyList.append(dfKey);
  1579. elif headerList0 == recoveryInfoDfs_header: # 被追偿信息
  1580. dfKey = "recoveryInfoDfs";
  1581. dfMap[dfKey]["dfs"].append({"df": df});
  1582. keyList.append(dfKey);
  1583. # 设置分页
  1584. dfMap[dfKey]["page"] = p + 1;
  1585. logger.info(fileName+"#"+"组装pdf数据完成")
  1586. logger.info(fileName+"#"+"解析基础pdf数据开始")
  1587. # 打印结果解析并构建指标
  1588. for key in dfMap:
  1589. tempDfObjx = dfMap[key];
  1590. if tempDfObjx.__contains__("page"):
  1591. logger.info(fileName+"#"+key + "-page-" + str(tempDfObjx["page"]))
  1592. if tempDfObjx.__contains__("dfs"):
  1593. if key == "loanDfs": # 贷款账户
  1594. for idx in range(0, len(tempDfObjx["dfs"])):
  1595. tempDfObj = tempDfObjx["dfs"][idx];
  1596. loanAccountDfs.append(dfParser.mergeLoanDf(tempDfObj, idx,queryInfo['reportTime']))
  1597. elif key == "creditCardDfs": # 贷记卡账户合并
  1598. for idx in range(0, len(tempDfObjx["dfs"])):
  1599. tempDfObj = tempDfObjx["dfs"][idx];
  1600. tempCreditCardDf = dfParser.mergeCreditCardDf(tempDfObj, idx,queryInfo['reportTime']);
  1601. if tempCreditCardDf!=None:
  1602. creditCardAccountDfs.append(tempCreditCardDf)
  1603. elif key == "creditCardDfsZ": # 贷记卡账户合并
  1604. for idx in range(0, len(tempDfObjx["dfs"])):
  1605. tempDfObj = tempDfObjx["dfs"][idx];
  1606. tempCreditCardDfZ = dfParser.mergeCreditCardDfZ(tempDfObj, idx,queryInfo['reportTime'])
  1607. if tempCreditCardDfZ!=None:
  1608. creditCardAccountDfsZ.append(tempCreditCardDfZ)
  1609. elif key == "recoveryInfoDfs": # 贷记卡账户合并
  1610. for idx in range(0, len(tempDfObjx["dfs"])):
  1611. tempDfObj = tempDfObjx["dfs"][idx];
  1612. recoveryInfoAccountDfs.append(dfParser.mergeRecoveryInfoDf(tempDfObj, idx, queryInfo['reportTime']))
  1613. elif key == "housingFundRcdDfs": # 贷记卡账户合并
  1614. for idx in range(0, len(tempDfObjx["dfs"])):
  1615. tempDfObj = tempDfObjx["dfs"][idx];
  1616. housingFundRcdAccountDfs.append(dfParser.mergeHousingFundRcdDf(tempDfObj, idx, queryInfo['reportTime']))
  1617. else: # 其他
  1618. for tempDfObj in (tempDfObjx["dfs"]):
  1619. if tempDfObj.__contains__("isByPage"):
  1620. logger.info(fileName+"#"+key + "============其他被分页页数============" + str(tempDfObj["isByPage"]))
  1621. # logger.info(fileName+"#"+tempDfObj["df"].values)
  1622. else: # 单笔
  1623. tempDfObj = tempDfObjx;
  1624. if tempDfObj.__contains__("isByPage"):
  1625. logger.info(fileName+"#"+key + "============被分页页数================" + str(tempDfObj["isByPage"]))
  1626. # logger.info(fileName+"#"+tempDfObj["df"].values)
  1627. if key == "queryInfoDf": # 解析被查询信息
  1628. parseQueryInfo(tempDfObj);
  1629. # print("\033[1;31m +查询信息+ \033[0m")
  1630. # print(queryInfo)
  1631. elif key == "identityDf": # 身份信息
  1632. parseIdentity(tempDfObj)
  1633. # print("\033[1;31m +身份信息+ \033[0m")
  1634. # print(identity)
  1635. elif key == "mateDf": # 配偶信息
  1636. parseMate(tempDfObj)
  1637. # print("\033[1;31m +配偶信息+ \033[0m")
  1638. # print(mate)
  1639. elif key == "liveInfoDf": # 居住信息
  1640. parseLiveInfo(tempDfObj)
  1641. # print("\033[1;31m +居住信息+ \033[0m")
  1642. elif key == "occupationDf": # 居住信息
  1643. parseOccupationInfoDf(tempDfObj)
  1644. elif key == "loanTradeInfoDf": # 信贷交易信息提示
  1645. parseLoanTradeInfo(tempDfObj);
  1646. # print("\033[1;31m +信贷交易信息提示+ \033[0m")
  1647. # print(loanTradeInfo)
  1648. elif key == "badDebtsInfoSumDf": # 呆账信息汇总
  1649. parseBadDebtsInfoSumDf(tempDfObj)
  1650. # print("\033[1;31m +呆账信息汇总+ \033[0m")
  1651. # print(overdueBrief)
  1652. elif key == "recoveryInfoSumDf": # 被追偿信息汇总-资产处置和垫款
  1653. parseRecoveryInfoSum(tempDfObj)
  1654. # print("\033[1;31m +资产处置和垫款+ \033[0m")
  1655. # print(overdueBrief)
  1656. elif key == "overdueInfoSumDf": # 逾期(透支)信息汇总
  1657. parseOverdueInfoSum(tempDfObj)
  1658. # print("\033[1;31m +逾期(透支)信息汇总+ \033[0m")
  1659. # print(overdueInfo)
  1660. elif key == "loanAccountInfoSumDf": # 非循环贷账户信息汇总 TODO
  1661. parseLoanAccountInfoSum(tempDfObj)
  1662. elif key == "cycleCreditAccountInfoSumDf":#循环额度
  1663. parseCycleCreditAccountInfoSum(tempDfObj)
  1664. elif key == "cycleLoanAccountInfoSumDf":#循环贷
  1665. parseCyleLoanAccountInfoSum(tempDfObj)
  1666. elif key == "creditCardInfoSumDf":#贷记卡
  1667. parseCreditCardInfoSum(tempDfObj)
  1668. elif key == "creditCardInfoSumDfZ": # 准贷记卡
  1669. parseCreditCardInfoSumZ(tempDfObj)
  1670. elif key == "repaymentSumDf": # 相关还款责任
  1671. parseRepaymentSum(tempDfObj)
  1672. elif key == "publicInfoBriefDf":
  1673. parsePublicInfoBrief(tempDfObj);
  1674. elif key == "queryRecordSumDf":
  1675. parseQueryRecordSum(tempDfObj);
  1676. elif key == "queryRecordDetailDf": # 查询记录明细
  1677. parseQueryInfoDetail(tempDfObj)#
  1678. logger.info(fileName+"#"+"解析基础pdf数据完成")
  1679. result = "{"
  1680. # 基本信息
  1681. # result+=("\033[1;34m +身份信息+ \033[0m")+"\n"
  1682. result+=utils.toJson(identityInfoDf)+","
  1683. result += utils.toJson(mateInfoDf) + ","
  1684. result += utils.toJson(liveInfoDf) + ","
  1685. result += utils.toJson(occupationInfoDf) + ","
  1686. # result+=("\033[1;34m +概要信息+ \033[0m")+","
  1687. # result+=("\033[1;34m +信贷交易信息提示+ \033[0m")+","
  1688. # result+=utils.toJson(briefInfoDf_loanTradeInfo)+","
  1689. result += "briefInfoDf_loanTradeInfo" + "," # 占位符
  1690. # result+=("\033[1;34m +被追偿信息汇总及呆账信息汇总+ \033[0m")+","
  1691. result+="briefInfoDf_recoveryInfoSum"+"," #占位符
  1692. result += utils.toJson(briefInfoDf_badDebtsInfoSum) + ","
  1693. # result+=("\033[1;34m +逾期(透支)信息汇总+ \033[0m")+","
  1694. #此信息先占位
  1695. result+="briefInfoDf_overdueInfoSum"+","
  1696. # result+=("\033[1;34m +信贷交易授信及负债信息概要+ \033[0m")+","
  1697. result+=utils.toJson(briefInfoDf_loanTradeCreditInfo)+","
  1698. #公共信息
  1699. result += utils.toJson(publicInfoBriefDf) + ","
  1700. #查询记录汇总
  1701. result += utils.toJson(queryRecordSumDf) + ","
  1702. # 单独输出贷款df
  1703. # logger.info(fileName+"#"+"\033[1;34m +贷款信息Dataframe+ \033[0m")
  1704. # logger.info(fileName+"#"+dfParser.dfHeaderLoan)
  1705. logger.info(fileName+"#"+pdf_path+"解析贷款数据开始")
  1706. loanMergeDf = pd.DataFrame(columns=dfParser.dfHeaderLoan)
  1707. loanPayRecordMergeDf = pd.DataFrame(columns=dfParser.dfHeaderLoanPayRecord)
  1708. loanSpecialTradeMergeDf = pd.DataFrame(columns=dfParser.dfHeaderLoanSpecialTrade)#特殊交易
  1709. # 输出数据
  1710. for loanDfObj in loanAccountDfs:
  1711. loanMergeDf = pd.concat([loanMergeDf, loanDfObj["loanDf"]], axis=0, ignore_index=True);
  1712. loanPayRecordMergeDf = pd.concat([loanPayRecordMergeDf, loanDfObj["loanPayRecordDf"]], axis=0,ignore_index=True);
  1713. loanSpecialTradeMergeDf = pd.concat([loanSpecialTradeMergeDf, loanDfObj["specialTradeDf"]], axis=0, ignore_index=True);
  1714. # logger.info(fileName+"#"+loanMergeDf.values)
  1715. # logger.info(fileName+"#"+"\033[1;34m +贷款信息还款记录Dataframe+ \033[0m")
  1716. # logger.info(fileName+"#"+dfParser.dfHeaderLoanPayRecord)
  1717. # logger.info(fileName+"#"+loanPayRecordMergeDf.values)
  1718. #
  1719. #==============================信贷交易明细 ===============================
  1720. #被追偿信息
  1721. # 被追偿信息合并df
  1722. recoveryInfoMergeDf = pd.DataFrame(columns=dfParser.dfHeaderRecoveryInfo)
  1723. for recoveryInfoDfObj in recoveryInfoAccountDfs:
  1724. recoveryInfoMergeDf = pd.concat([recoveryInfoMergeDf, recoveryInfoDfObj["recoveryInfoDf"]], axis=0,
  1725. ignore_index=True);
  1726. parseRecoveryInfoMergeDf(recoveryInfoMergeDf);
  1727. #被追偿信息
  1728. result = result.replace("briefInfoDf_recoveryInfoSum", utils.toJson(briefInfoDf_recoveryInfoSum))#替换汇总中的指标
  1729. result += utils.toJson(creditTradeDetailDf_recoveryInfo) + "," #设置占位符,由于存在概要的指标在明细中计算
  1730. #特殊交易
  1731. parseSpecialTrade(loanSpecialTradeMergeDf)
  1732. result += utils.toJson(creditTradeDetailHeader_specialTrade) + ","
  1733. # 信贷交易明细-解析非循环贷账户
  1734. parseLoanAccountInfo(loanMergeDf);
  1735. result += utils.toJson(creditTradeDetailDf_loanAccountInfo) + ","
  1736. #循环额度分账户
  1737. parseCycleCreditAccountInfo(loanMergeDf);
  1738. result += utils.toJson(creditTradeDetailDf_cycleCreditAccountInfo) + ","
  1739. #循环贷
  1740. parseCycleLoanAccountInfo(loanMergeDf);
  1741. result += utils.toJson(creditTradeDetailDf_cycleLoanAccountInfo) + ","
  1742. # 解析贷款账户指标
  1743. parseLoanMergeDf(loanMergeDf);
  1744. # 解析还款记录相关指标
  1745. parseLoanMergeAndPayRecordDf(loanMergeDf, loanPayRecordMergeDf);
  1746. # logger.info(fileName+"#"+loanAccountInfo)
  1747. # logger.info(fileName+"#"+consts.loanAccountInfoHeader)
  1748. # logger.info(fileName+"#"+loanAccountInfoDf.values)
  1749. # result+=("\033[1;34m +贷款账户信息+ \033[0m")+","
  1750. result+=utils.toJson(loanAccountInfoDf)+","
  1751. logger.info(fileName+"#"+"解析贷款数据完成")
  1752. logger.info(fileName+"#"+"解析贷记卡数据开始")
  1753. #贷记卡合并df
  1754. creditCardMergeDf = pd.DataFrame(columns=dfParser.dfHeaderCreditCard)
  1755. creditCardPayRecordMergeDf = pd.DataFrame(columns=dfParser.dfHeaderCreditCardPayRecord)
  1756. # logger.info(fileName+"#"+"\033[1;34m +贷记卡信息Dataframe+ \033[0m")
  1757. # logger.info(fileName+"#"+dfParser.dfHeaderCreditCard)
  1758. # 输出数据
  1759. for creditCardDfObj in creditCardAccountDfs:
  1760. creditCardMergeDf = pd.concat([creditCardMergeDf, creditCardDfObj["creditCardDf"]], axis=0, ignore_index=True);
  1761. creditCardPayRecordMergeDf = pd.concat([creditCardPayRecordMergeDf, creditCardDfObj["creditCardPayRecordDf"]], axis=0,ignore_index=True);
  1762. # logger.info(fileName+"#"+creditCardMergeDf.values)
  1763. # 解析贷记卡账户指标
  1764. parseCreditCardMergeDf(creditCardMergeDf);
  1765. parseCreditCardMergeAndPayRecordDf(creditCardMergeDf,creditCardPayRecordMergeDf)
  1766. #准贷记卡合并df
  1767. creditCardMergeDfZ = pd.DataFrame(columns=dfParser.dfHeaderCreditCardZ)
  1768. creditCardPayRecordMergeDfZ = pd.DataFrame(columns=dfParser.dfHeaderCreditCardPayRecordZ)
  1769. for creditCardDfObj in creditCardAccountDfsZ:
  1770. creditCardMergeDfZ = pd.concat([creditCardMergeDfZ, creditCardDfObj["creditCardDfZ"]], axis=0, ignore_index=True);
  1771. creditCardPayRecordMergeDfZ = pd.concat([creditCardPayRecordMergeDfZ, creditCardDfObj["creditCardPayRecordDfZ"]], axis=0,ignore_index=True);
  1772. #解析准贷记卡相关指标
  1773. parseCreditCardMergeDfZ(creditCardMergeDfZ,creditCardPayRecordMergeDfZ);
  1774. logger.info(fileName+"#"+"解析贷记卡数据完成")
  1775. #加工使用率指标
  1776. # result+=("\033[1;34m +贷记卡账户信息+ \033[0m")+","
  1777. result+=utils.toJson(creditCardAccountInfoDf)+","
  1778. result += utils.toJson(creditCardAccountInfoDfZ) + ","
  1779. #使用率
  1780. parseUseRate()
  1781. result += utils.toJson(useRateDf) + ","
  1782. #开户数
  1783. parseOpenAccount(loanMergeDf, creditCardMergeDf, creditCardMergeDfZ,recoveryInfoMergeDf,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ)
  1784. result += utils.toJson(openAccountDf) + ","
  1785. #24期还款状态
  1786. parsePayRcdStatus(loanMergeDf, creditCardMergeDf, creditCardMergeDfZ,loanPayRecordMergeDf,creditCardPayRecordMergeDf,creditCardPayRecordMergeDfZ)
  1787. result += utils.toJson(payRcdStatusDf) + ","
  1788. #由于逾期汇总的指标再还款状态之后需要替换占位 TODO
  1789. result = result.replace("briefInfoDf_overdueInfoSum",utils.toJson(briefInfoDf_overdueInfoSum))
  1790. #0525 由于在开户数后,统计信贷信息概要的指标,替换占位符
  1791. result = result.replace("briefInfoDf_loanTradeInfo", utils.toJson(briefInfoDf_loanTradeInfo))
  1792. #公积金
  1793. # 被追偿信息合并df
  1794. housingFundRcdMergeDf = pd.DataFrame(columns=dfParser.dfHeaderHousingFundRcd)
  1795. for housingFundRcdDfObj in housingFundRcdAccountDfs:
  1796. housingFundRcdMergeDf = pd.concat([housingFundRcdMergeDf, housingFundRcdDfObj["housingFundRcdDf"]], axis=0,ignore_index=True);
  1797. parseHousingFundRcd(housingFundRcdMergeDf);
  1798. result += utils.toJson(housingFundRcdDf) + ","
  1799. # result+=("\033[1;34m +查询记录明细+ \033[0m")+","
  1800. result+=utils.toJson(queryRecordDetailDf)+""
  1801. result +="}"
  1802. return result;
  1803. #调用jar包
  1804. def invokePboc(basePath,pdf_path):
  1805. # ===================================
  1806. try:
  1807. # logger.error(pdf_path)
  1808. # fileName = os.path.basename(pdf_path)
  1809. # logger.error(fileName)
  1810. # jsonFileName = fileName.replace("pdf", 'txt')
  1811. businessNum = dbController.getBussinessNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1812. coopBussinessNum = dbController.getCoopBussinessNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1813. pboc = PBOC()
  1814. jarTxt = pboc.calc(pdf_path.replace("pdf", 'txt'),coopBussinessNum);
  1815. result = json.loads(jarTxt)
  1816. logger.info(result)
  1817. if result.get("errcode")== None:
  1818. uploadAudit(result,businessNum)
  1819. else:
  1820. logger.error(result["errmsg"])
  1821. except:
  1822. info = sys.exc_info()
  1823. logger.error(info[0])
  1824. logger.error(info[1])
  1825. # logging.log(logging.ERROR, info[2])
  1826. logger.error(traceback.extract_tb(info[2], 1))
  1827. #调用xxwjar包
  1828. def invokeXxw(basePath,pdf_path):
  1829. # ===================================
  1830. try:
  1831. # logger.error(pdf_path)
  1832. # fileName = os.path.basename(pdf_path)
  1833. # logger.error(fileName)
  1834. # jsonFileName = fileName.replace("pdf", 'txt')
  1835. businessNum = dbController.getBussinessNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1836. coopBussinessNum = dbController.getCoopBussinessNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1837. customerNum = dbController.getCustomerNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1838. pboc = PBOC()
  1839. jarTxt = pboc.calcXxw(coopBussinessNum,customerNum,pdf_path.replace("pdf", 'txt'));
  1840. logger.info(jarTxt)
  1841. result = json.loads(jarTxt)
  1842. logger.info(result)
  1843. # jsonPath = pdf_path.replace(".pdf", ".txt");
  1844. # file_name = os.path.basename(pdf_path)
  1845. # jsonPath = basePath+file_name
  1846. jsonPath = basePath+queryInfo["queryInfoCardId"]+".txt"
  1847. logger.info(jsonPath)
  1848. with open(jsonPath, 'w') as fp:
  1849. fp.write(jarTxt)
  1850. uploadReportResultXxw(jsonPath)
  1851. # descPdfPath = basePath + "execed_new/" + os.path.basename(pdf_path)
  1852. # if not os.path.exists(basePath + "execed_new/"):
  1853. # os.mkdir(basePath + "execed_new/")
  1854. # logger.info("移动文件 from " + pdf_path + " to " + descPdfPath)
  1855. # shutil.move(pdf_path, descPdfPath)
  1856. descJsonPath = basePath + "execed_txt/" + os.path.basename(jsonPath)
  1857. shutil.move(jsonPath, descJsonPath)
  1858. # descTxtPath = descPdfPath.replace(".pdf",".txt")
  1859. # txtPath = pdf_path.replace("pdf", 'txt')
  1860. # shutil.move(txtPath, descTxtPath)
  1861. except:
  1862. info = sys.exc_info()
  1863. logger.error(info[0])
  1864. logger.error(info[1])
  1865. # logging.log(logging.ERROR, info[2])
  1866. logger.error(traceback.extract_tb(info[2], 1))
  1867. #上传审批结果
  1868. def uploadAudit(result,businessNum):
  1869. approvalType = result["approveResult"]
  1870. if approvalType=="1":
  1871. approvalOpinion = "征信通过"
  1872. approvalType = "4"
  1873. else:
  1874. approvalOpinion = "征信拒绝"
  1875. approvalType = "3"
  1876. taskKey = config.get("baseconf","taskKey")
  1877. appoveApiUrl = config.get("baseconf","appoveApiUrl")
  1878. key = config.get("baseconf", "AESKey")
  1879. data = {"header":{
  1880. "ticket": "2938123198320412343",
  1881. "timestamp": int(int(round(time.time() * 1000+60*1000))),
  1882. "nonce": config.get("baseconf", "nonce")
  1883. },
  1884. "body":{"approvalType": approvalType, "businessNum": businessNum,"taskKey":taskKey,"approvalOpinion":approvalOpinion}}
  1885. access_token = dbController.getToken()
  1886. appoveApiUrl = appoveApiUrl+"?access_token="+access_token
  1887. headers = {"Content-Type": "application/json"}
  1888. jsonStr = json.dumps(data);
  1889. jsonStr = jsonStr.replace('"',"\\\"")#必须替换才行
  1890. logger.info(jsonStr)
  1891. pboc = PBOC();
  1892. encryData = pboc.encrypt(jsonStr,key)
  1893. encryData = encryData[0:len(encryData)-2]
  1894. logger.info(encryData)
  1895. response = requests.post(appoveApiUrl, data=encryData,headers=headers)
  1896. text = response.text
  1897. # p = PrpCrypt(key)
  1898. pboc = PBOC();
  1899. resultText = pboc.decrypt(text, config.get("baseconf", "AESKey"))
  1900. # resultText = p.decrypt(text)
  1901. logger.info(businessNum + "#" + "uploadAudit upload_result:" + resultText)
  1902. def uploadReportResult(basePath,pdf_path):
  1903. # ===================================
  1904. try:
  1905. fileName = os.path.basename(pdf_path)
  1906. #上传文件逻辑
  1907. logger.info(fileName+"#"+fileName+"#"+"准备上传文件")
  1908. uploadApiUrl = config.get("baseconf", "uploadApiUrl");
  1909. uploadApiUrl = uploadApiUrl + "?access_token=" + dbController.getToken()
  1910. files = {'file': open(outPath, 'rb')}
  1911. businessNum = dbController.getBussinessNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1912. logger.info(fileName+"#"+fileName+"#"+"businessNum:"+businessNum)
  1913. logger.info(fileName+"#"+"queryInfoCardId:" + queryInfo["queryInfoCardId"])
  1914. data = {'docType': "23", 'businessNum': businessNum}
  1915. response = requests.post(uploadApiUrl, files=files, data=data)
  1916. text = response.text
  1917. # p = PrpCrypt(config.get("baseconf", "AESKey"))
  1918. # logger.info(fileName+"#"+"token:"+token)
  1919. # logger.info(fileName+"#"+url)
  1920. # logger.info(fileName+"#"+result.text)
  1921. pboc = PBOC();
  1922. resultText = pboc.decrypt(text, config.get("baseconf", "AESKey"))
  1923. logger.info(fileName+"#"+"upload_result:" + resultText)
  1924. descPdfPath = basePath + "execed_new/" + os.path.basename(pdf_path)
  1925. if not os.path.exists(basePath+"execed_new/"):
  1926. os.mkdir(basePath+"execed_new/")
  1927. logger.info("移动文件 from " + pdf_path+" to "+descPdfPath)
  1928. shutil.move(pdf_path, descPdfPath)
  1929. except:
  1930. info = sys.exc_info()
  1931. logger.error(info[0])
  1932. logger.error(info[1])
  1933. # logging.log(logging.ERROR, info[2])
  1934. logger.error(traceback.extract_tb(info[2], 1))
  1935. def uploadReportResultXxw(json_path):
  1936. # ===================================
  1937. try:
  1938. fileName = os.path.basename(json_path)
  1939. #上传文件逻辑
  1940. logger.info("#"+json_path+"#"+"准备上传文件")
  1941. uploadApiUrl = config.get("baseconf", "uploadApiUrl");
  1942. uploadApiUrl = uploadApiUrl + "?access_token=" + dbController.getToken()
  1943. files = {'file': open(json_path, 'rb')}
  1944. businessNum = dbController.getBussinessNum(queryInfo["queryInfoCardId"]); # 根据身份证获取业务编号
  1945. logger.info(fileName+"#"+fileName+"#"+"businessNum:"+businessNum)
  1946. logger.info(fileName+"#"+"queryInfoCardId:" + queryInfo["queryInfoCardId"])
  1947. data = {'docType': "23", 'businessNum': businessNum}
  1948. response = requests.post(uploadApiUrl, files=files, data=data)
  1949. text = response.text
  1950. logger.info("上传结果:"+text)
  1951. pboc = PBOC();
  1952. resultText = pboc.decrypt(text,config.get("baseconf", "AESKey"))
  1953. logger.info(fileName+"#"+"uploadReportResultXxw:" + resultText)
  1954. except:
  1955. info = sys.exc_info()
  1956. logger.error(info[0])
  1957. logger.error(info[1])
  1958. # logging.log(logging.ERROR, info[2])
  1959. logger.error(traceback.extract_tb(info[2], 1))
  1960. def updateParseInd(file_name):
  1961. # 检查是否存在已执行
  1962. parseInd = "1"
  1963. try:
  1964. if file_name != "":
  1965. arCert = file_name[0:-4].split("_")
  1966. if len(arCert) == 2:
  1967. cert_id = arCert[1]
  1968. parseIndTmp = dbController.getParseInd(cert_id)
  1969. if parseIndTmp =="1":
  1970. return True
  1971. dbController.updateParseInd(cert_id, parseInd)
  1972. except:
  1973. logger.error("update parse ind error")
  1974. return False
  1975. # grouped.to_csv(r'C:\Users\Mortal\Desktop\ex.csv',index=False, encoding='utf_8_sig')
  1976. def moveFile(basePath,pdf_path):
  1977. descPdfPath = basePath + "execed_new/" + os.path.basename(pdf_path)
  1978. if not os.path.exists(basePath + "execed_new/"):
  1979. os.mkdir(basePath + "execed_new/")
  1980. logger.info("移动文件 from " + pdf_path + " to " + descPdfPath)
  1981. shutil.move(pdf_path, descPdfPath)
  1982. descTxtPath = basePath + "execed_txt/" + os.path.basename(pdf_path).replace("pdf", 'txt')
  1983. if not os.path.exists(basePath + "execed_txt/"):
  1984. os.mkdir(basePath + "execed_txt/")
  1985. txtPath = pdf_path.replace("pdf", 'txt')
  1986. shutil.move(txtPath, descTxtPath)
  1987. if __name__ == '__main__':
  1988. file_name = ""
  1989. # basePath = "D:/mydocument/myproject/git/busscredit/20200414_report/";
  1990. basePath = "D:/mydocument/myprojects/creditreport/parse/"
  1991. # basePath = "Z:/cr/parse/"
  1992. # file_name = "周颖500108199002111229.pdf"#准贷记卡已销户 呆账
  1993. # file_name = "王思13052819911012122X.pdf"#公积金
  1994. # file_name = "杨夏龙440902198410014270.pdf"#转出
  1995. # file_name = "翟彦超230125199004174216.pdf"#准贷记卡 呆账
  1996. # file_name = "蔡月辉330326198502116146.pdf" # 配偶
  1997. # file_name = "周芳芳342501198706111782.pdf" #被追偿信息
  1998. # file_name = "付春雁533001198507220344.pdf" # 公积金记录
  1999. # pdf_path = basePath + "陈洁350122199005027726.pdf" # 相关还款责任
  2000. # file_name = "叶翔_330126197005200077.pdf" # 准贷记卡分页
  2001. file_name = "曹玉巧_320323198012082085.pdf" #
  2002. # file_name = "姚钧_120101198903033539.pdf" #
  2003. pdf_path = basePath + file_name
  2004. if len(sys.argv)>1:
  2005. basePath = sys.argv[1]
  2006. pdf_path = basePath + sys.argv[2]
  2007. file_name = sys.argv[2]
  2008. # print(sys.argv)
  2009. isBat = False#批量的有问题
  2010. isPlt = config.get("baseconf", "isPlt");
  2011. if isBat:#批量生成数据不对
  2012. for file in os.listdir(basePath):
  2013. if file.endswith("pdf"):
  2014. start = timeit.default_timer();
  2015. pdf_path = basePath+file;
  2016. outPath = pdf_path.replace("pdf",'txt')
  2017. if os.path.exists(outPath):
  2018. continue;
  2019. logger.info(file + "解析开始...")
  2020. try:
  2021. result = main(pdf_path)
  2022. except:
  2023. info = sys.exc_info()
  2024. logger.error(info[0])
  2025. logger.error( info[1])
  2026. # logging.log(logging.ERROR, info[2])
  2027. logger.error(traceback.extract_tb(info[2], 1))
  2028. # print(result)
  2029. #输出到文件
  2030. sys.stdout = open(outPath, mode='w', encoding='utf-8')
  2031. print(result.replace("\033[1;34m","").replace("\033[0m",""))
  2032. logger.info(file+"解析完成")
  2033. gc.collect()
  2034. s = timeit.default_timer() - start;
  2035. logger.info(str(s) + " 秒")
  2036. else:
  2037. if pdf_path.endswith("pdf"):
  2038. start = timeit.default_timer();
  2039. outPath = pdf_path.replace("pdf", 'txt')
  2040. result = ""
  2041. if isPlt == "1":#生产模式
  2042. if not os.path.exists(outPath):#不存在才生成
  2043. try:
  2044. isExec = updateParseInd(file_name)
  2045. if not isExec:#没有在执行
  2046. logger.info(file_name + "解析开始...")
  2047. result = main(pdf_path)
  2048. # sys.stdout = open(outPath, mode='w', encoding='utf-8')
  2049. # print(result.replace("\033[1;34m", "").replace("\033[0m", ""))
  2050. with open(outPath, 'w', encoding='utf-8') as fp:
  2051. fp.write(result)
  2052. logger.info(file_name + "解析完成")
  2053. s = timeit.default_timer() - start;
  2054. logger.info(file_name+"#"+str(s) + " 秒")
  2055. #调用jar计算审批结果
  2056. cert_id = queryInfo["queryInfoCardId"]
  2057. productNum = dbController.getProductNum(cert_id)
  2058. if productNum != "":
  2059. if productNum == productNumJz:
  2060. # uploadReportResult(basePath, pdf_path);
  2061. invokePboc(basePath, pdf_path);
  2062. elif productNum == productNumXxw:
  2063. invokeXxw(basePath, pdf_path);
  2064. #移动pdf和txt文件,新希望移动json
  2065. moveFile(basePath, pdf_path)
  2066. # elif productNumXy.find(productNum) >= 0:
  2067. # xyHttp.call_credit(result)
  2068. # else:
  2069. # try:
  2070. # businessNum = dbController.getBussinessNum(queryInfo["queryInfoCardId"]);
  2071. # localJarResult = xyHttp.callLocal(result)
  2072. # if localJarResult.get("errcode") == None:
  2073. # uploadAudit(localJarResult, businessNum)
  2074. # else:
  2075. # logger.error(localJarResult["errmsg"])
  2076. # except:
  2077. # info = sys.exc_info()
  2078. # logger.error(info[0])
  2079. # logger.error(info[1])
  2080. # # logging.log(logging.ERROR, info[2])
  2081. # logger.error(traceback.extract_tb(info[2], 1))
  2082. except:
  2083. info = sys.exc_info()
  2084. logger.error(file_name+"#"+"解析失败")
  2085. logger.error(info[0])
  2086. logger.error(info[1])
  2087. logger.error(traceback.extract_tb(info[2]))
  2088. else:#如果已经执行过了,移动文件
  2089. logger.info("移动文件"+pdf_path)
  2090. # descPdfPath = basePath + "execed/" + os.path.basename(pdf_path)
  2091. # if not os.path.exists(basePath + "execed/"):
  2092. # os.mkdir(basePath + "execed/")
  2093. # shutil.move(pdf_path, descPdfPath)
  2094. else:
  2095. isExec = updateParseInd(file_name)
  2096. if not isExec: # 没有在执行
  2097. result = main(pdf_path)
  2098. # sys.stdout = open(outPath, mode='w', encoding='utf-8')
  2099. # print(result.replace("\033[1;34m", "").replace("\033[0m", ""))
  2100. with open(outPath, 'w', encoding='utf-8') as fp:
  2101. fp.write(result)
  2102. logger.info(file_name + "解析完成")
  2103. s = timeit.default_timer() - start;
  2104. logger.info(file_name+"#"+str(s) + " 秒")
  2105. # uploadReportResult(basePath,pdf_path);
  2106. # 调用jar计算审批结果
  2107. cert_id = queryInfo["queryInfoCardId"]
  2108. productNum = dbController.getProductNum(cert_id)
  2109. if productNum != "":
  2110. if productNum == productNumJz:
  2111. invokePboc(basePath, pdf_path);
  2112. elif productNum == productNumXxw:
  2113. invokeXxw(basePath, pdf_path);
  2114. # elif productNumXy.find(productNum) >= 0:
  2115. # xyHttp.call_credit(result)
  2116. # else:
  2117. # try:
  2118. # businessNum = dbController.getBussinessNum(queryInfo["queryInfoCardId"]);
  2119. # localJarResult = xyHttp.callLocal(result)
  2120. # if localJarResult.get("errcode") == None:
  2121. # uploadAudit(localJarResult, businessNum)
  2122. # else:
  2123. # logger.error(localJarResult["errmsg"])
  2124. # except:
  2125. # info = sys.exc_info()
  2126. # logger.error(info[0])
  2127. # logger.error(info[1])
  2128. # # logging.log(logging.ERROR, info[2])
  2129. # logger.error(traceback.extract_tb(info[2], 1))