parseCreditPdf.py0820 160 KB

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