mvp.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. from mysql_db import MysqlDB
  2. from excel_util import ExcelUtil
  3. import time
  4. from entity import PeopleInfo
  5. import random
  6. class Mvp:
  7. """
  8. ce mvp 答题数据统计
  9. 城市特例 北京市,上海市, 重庆市,天津市
  10. """
  11. age_dict = {
  12. '00-04年生': '95后',
  13. '05-09年生': '05后',
  14. '50-59年生': '50后',
  15. '60-69年生': '60后',
  16. '70-74年生': '70后',
  17. '75-79年生': '75后',
  18. '80-84年生': '80后',
  19. '85-89年生': '85后',
  20. '90-94年生': '85后',
  21. '95-99年生': '95后'
  22. }
  23. age_list = ['85后', '95后']
  24. city_list = ['上海市', '上海周边']
  25. # 用户画像-消费结构 用户画像-生活方式
  26. # 需要更新的模块:用户画像-性别、用户画像-行业、用户画像-出行方式、
  27. # 用户画像-消费结构、用户画像-生活方式、用户画像-社交模式、用户画像-审美偏好
  28. tag_table = {
  29. '用户画像-审美偏好': ['mvp_crowd_info_aesthetic_preference', 'aesthetic_preference'],
  30. '用户画像-行为兴趣': ['mvp_crowd_info_behavior', 'behavioral_interest'],
  31. '用户画像-消费观念': ['mvp_crowd_info_consumer_concept', 'consumer_concept'],
  32. '用户画像-社交模式': ['mvp_crowd_info_social_mode', 'social_module'],
  33. '用户画像-行业': ['mvp_crowd_info_trade', 'trade'],
  34. '用户画像-出行方式': ['mvp_crowd_info_trip_mode', 'trip_mode'],
  35. '空间需求图谱-色相': ['mvp_innovate_space_hue_prefer', 'hue'],
  36. '空间需求图谱-精装关注点': ['mvp_innovate_space_hardcover_focus', 'hardcover_focus'],
  37. '空间需求图谱-色调': ['mvp_innovate_space_hue_prefer', 'hue'],
  38. '空间需求图谱-单品偏好': ['mvp_innovate_space_item_preference', 'item_preference'],
  39. '空间需求图谱-材质': ['mvp_innovate_space_material_prefer', 'material'],
  40. '空间需求图谱-空间特性偏好': ['mvp_innovate_space_space_prefer', 'space_preference'],
  41. '模块分数': ['mvp_crowd_info_module', 'module_name'],
  42. '用户画像-生活方式': ['mvp_crowd_info_life_style', 'life_style'],
  43. '用户画像-消费结构': ['mvp_crowd_info_consumer_structure', 'consumer_structure']
  44. }
  45. crowd_info_1 = {
  46. '1973': 'A',
  47. '1974': 'B',
  48. '1975': 'C',
  49. '1976': 'D',
  50. '1977': 'E',
  51. '1978': 'F',
  52. '1979': 'G',
  53. '1813': 'A',
  54. '1814': 'B',
  55. '1815': 'C',
  56. '1816': 'D',
  57. '1817': 'E',
  58. '1818': 'F',
  59. '1819': 'G'
  60. }
  61. base_insert_sql = '''
  62. INSERT INTO {} (
  63. crowd_info_id,
  64. {},
  65. standard_value,
  66. STATUS,
  67. creator,
  68. created
  69. )
  70. VALUES
  71. (%s, %s, %s, 1, 'binren', now())
  72. '''
  73. def get_table_name(self, name):
  74. """
  75. 获取表名
  76. :param name:
  77. :return:
  78. """
  79. params = self.tag_table.get(name)
  80. if params:
  81. return self.tag_table.get(name)[0]
  82. def get_insert_sql(self, tag_type_name):
  83. """
  84. 根据标签分类名称获取相应表的插入sql
  85. :param tag_type_name:
  86. :return:
  87. """
  88. params = self.tag_table.get(tag_type_name)
  89. if params:
  90. return self.base_insert_sql.format(params[0], params[1])
  91. crowd = ['A', 'B', 'C', 'D', 'E', 'F']
  92. # 获取答题记录中城市列表
  93. sql_1 = 'select city from f_t_daren_score_2 group by city'
  94. # 获取父选项和父题id
  95. sql_2 = 'select a.id, a.content, b.id, b.name from bq_option a left join bq_question b on a.question_id = b.id ' \
  96. 'where a.serial_number = %s and b.serial_number = %s and a.status = b.status = 1 '
  97. # 获取答题人的年龄段集合
  98. sql_4 = 'select nld from f_t_daren_score_2 group by nld'
  99. # 根据城市,年龄段,人群分类统计答题记录数
  100. sql_5 = 'select testcase_id, COUNT(DISTINCT uuid) from f_t_daren_score_2 where uuid in %s group by testcase_id '
  101. # 根据父选项获取子选项id列表
  102. sql_6 = '''
  103. SELECT
  104. c.id,
  105. c.sub_question_id,
  106. c.content
  107. FROM
  108. bq_sub_option c
  109. WHERE
  110. c.father_id IN (
  111. SELECT
  112. a.id
  113. FROM
  114. bq_option a
  115. LEFT JOIN bq_question b ON a.question_id = b.id
  116. WHERE
  117. a.serial_number = % s
  118. AND b.serial_number = % s
  119. AND a. STATUS = 1
  120. AND b. STATUS = 1
  121. )
  122. AND c. STATUS = 1
  123. '''
  124. # 根据子题id获取包含子题id的测试
  125. sql_7 = 'select id from bq_testcase where status = 1 and FIND_IN_SET(%s, question_ids)'
  126. # 根据子选项id统计答题数
  127. sql_8 = '''
  128. SELECT
  129. count(DISTINCT a.uuid)
  130. FROM
  131. f_t_daren_score_2 a
  132. LEFT JOIN d_shangju_tiku_02 b ON a.sub_question_id = b.sub_question_id
  133. AND (
  134. a.score = b.score
  135. OR a.score = b.sub_option_id
  136. )
  137. AND a.testcase_id = b.testcase_id
  138. WHERE
  139. b.sub_option_id IN % s
  140. AND a.uuid IN % s
  141. '''
  142. # 获取一个uuid下答题的子选项id列表
  143. sql_10 = 'select DISTINCT uuid, GROUP_CONCAT(DISTINCT b.sub_option_id) from f_t_daren_score_2 a left join ' \
  144. 'd_shangju_tiku_02 b on a.sub_question_id = b.sub_question_id and (a.score = b.score or a.score = ' \
  145. 'b.sub_option_id) where a.status = ' \
  146. 'b.status = 1 group by uuid '
  147. # 向表mvp_crowd_info插入数据
  148. sql_11 = 'insert into mvp_crowd_info(age_area, city_name, crowd_type, status) values(%s, %s, %s, 1)'
  149. # 向表mvp_crowd_info_behavior中插入数据
  150. sql_12 = 'insert into mvp_crowd_info_behavior(crowd_info_id, behavioral_interest, standard_value, status) values(' \
  151. '%s, %s, ' \
  152. '%s, 1) '
  153. # 向表mvp_crowd_info_module中插入数据
  154. sql_13 = 'insert into mvp_crowd_info_module(crowd_info_id, module_name, standard_value, status) values (%s, %s, ' \
  155. '%s, 1) '
  156. sql_14 = 'select a.id, a.age_area, a.city_name, a.crowd_type from mvp_crowd_info a where a.status = 1'
  157. # 获取答题城市信息from city
  158. sql_15 = '''
  159. SELECT
  160. a.uuid,
  161. IFNULL(GROUP_CONCAT(DISTINCT a.city, a.province), 00) AS city,
  162. IFNULL(GROUP_CONCAT(DISTINCT a.nld), 00) AS nld,
  163. IFNULL(GROUP_CONCAT(DISTINCT a.sex), 00) AS sex,
  164. IFNULL(GROUP_CONCAT(DISTINCT b.sub_option_id), 00) as sub_option_ids,
  165. IFNULL(GROUP_CONCAT(DISTINCT a.testcase_id), 00) as testcase_ids
  166. FROM
  167. f_t_daren_score_2 a
  168. LEFT JOIN d_shangju_tiku_02 b ON a.testcase_id = b.testcase_id
  169. WHERE
  170. a.testcase_id = b.testcase_id
  171. AND a.sub_question_id = b.sub_question_id
  172. AND (
  173. a.score = b.score
  174. OR a.score = b.sub_option_id
  175. )
  176. GROUP BY
  177. a.uuid
  178. '''
  179. # 根据用户uuid获取城市信息
  180. sql_16 = '''
  181. SELECT
  182. a.uuid,
  183. b.sub_option_content
  184. FROM
  185. f_t_daren_score_2 a
  186. LEFT JOIN d_shangju_tiku_02 b ON a.testcase_id = b.testcase_id
  187. WHERE
  188. a.sub_question_id = b.sub_question_id
  189. AND (
  190. a.score = b.score
  191. OR a.score = b.sub_option_id
  192. )
  193. AND a.uuid = %s
  194. AND b.father_id = 249
  195. AND a. STATUS = b. STATUS = 1
  196. '''
  197. # 答题人人群分类信息
  198. sql_17 = '''
  199. SELECT
  200. a.uuid,
  201. b.sub_option_id
  202. FROM
  203. f_t_daren_score_2 a
  204. LEFT JOIN d_shangju_tiku_02 b ON a.testcase_id = b.testcase_id
  205. WHERE
  206. a.sub_question_id = b.sub_question_id
  207. AND (
  208. a.score = b.score
  209. OR a.score = b.sub_option_id
  210. )
  211. AND a.uuid = %s
  212. AND b.father_id = 236
  213. AND a.STATUS = b.STATUS = 1
  214. '''
  215. sql_18 = '''
  216. DELETE
  217. FROM
  218. mvp_crowd_info_behavior
  219. WHERE
  220. FIND_IN_SET(crowd_info_id, (
  221. SELECT
  222. GROUP_CONCAT(id)
  223. FROM
  224. mvp_crowd_info
  225. WHERE
  226. city_name = '上海市'
  227. AND age_area = '85后'
  228. AND STATUS = 1
  229. ))
  230. '''
  231. # 根据名称获取图标
  232. sql_19 = '''
  233. SELECT
  234. id,
  235. NAME
  236. FROM
  237. mvp_icon
  238. WHERE status = 1
  239. '''
  240. # 行为更新图标
  241. sql_20 = '''
  242. UPDATE mvp_crowd_info_behavior
  243. SET icon_id = % s
  244. WHERE
  245. behavioral_interest = % s
  246. '''
  247. # 模块图标更新
  248. sql_21 = '''
  249. '''
  250. # 更新性别占比数据
  251. sql_22 = '''
  252. INSERT INTO mvp_crowd_info_gender_rate (
  253. crowd_info_id,
  254. gender,
  255. standard_value,
  256. status,
  257. creator,
  258. created
  259. )
  260. VALUES
  261. (%s, %s, %s, 1, 'binren', now())
  262. '''
  263. sql_23 = '''
  264. DELETE
  265. FROM
  266. mvp_crowd_info_module
  267. WHERE
  268. FIND_IN_SET(crowd_info_id, (
  269. SELECT
  270. GROUP_CONCAT(id)
  271. FROM
  272. mvp_crowd_info
  273. WHERE
  274. city_name = '上海市'
  275. AND age_area = '85后'
  276. AND STATUS = 1
  277. ))
  278. '''
  279. """
  280. 数据debug SQL
  281. 1:
  282. SELECT
  283. c.id,
  284. c.sub_question_id,
  285. c.content
  286. FROM
  287. bq_sub_option c
  288. WHERE
  289. c.father_id IN (
  290. SELECT
  291. a.id
  292. FROM
  293. bq_option a
  294. LEFT JOIN bq_question b ON a.question_id = b.id
  295. WHERE
  296. a.serial_number ='FA001'
  297. AND b.serial_number = 'F00245'
  298. AND a. STATUS = 1
  299. AND b. STATUS = 1
  300. )
  301. AND c.STATUS = 1
  302. 2:
  303. select id from bq_testcase where status = 1 and FIND_IN_SET(%s, question_ids)
  304. 3:
  305. SELECT
  306. count(1)
  307. FROM
  308. f_t_daren_score_2 a
  309. LEFT JOIN d_shangju_tiku_02 b ON a.sub_question_id = b.sub_question_id
  310. AND (
  311. a.score = b.score
  312. OR a.score = b.sub_option_id
  313. )
  314. AND a.testcase_id = b.testcase_id
  315. WHERE
  316. b.sub_option_id IN (1964,1965,1966,1967,1968,1969,1970,1971,1972)
  317. """
  318. def __init__(self, path=None):
  319. self.shangju_db = MysqlDB('shangju')
  320. self.marketing_db = MysqlDB('bi_report')
  321. self.linshi_db = MysqlDB('linshi', db_type=1)
  322. # self.shangju_db.truncate('mvp_standard_score')
  323. self.tag_data = ExcelUtil(file_name=path).init_mvp_data()
  324. self.crowd_info = ExcelUtil(file_name=path, sheet_name='选项-人群分类对应表').init_crowd_info()
  325. self.citys = self.init_city()
  326. self.age = self.init_age()
  327. self.people_sub_option_ids = self.marketing_db.select(self.sql_10)
  328. self.crowd_contain_sub_option_ids = self.get_crowd_contain_sub_option_ids()
  329. self.module_scores = ExcelUtil(file_name='module.xlsx', sheet_name='行为-模块映射表').module_behavior_info()
  330. # self.scores_tag = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='行为').init_scores()
  331. # self.score_module = ExcelUtil(file_name='行为与模块分值汇总.xlsx', sheet_name='模块').init_scores()
  332. self.people_info_1 = self.people_info()
  333. def close(self):
  334. self.shangju_db.close()
  335. self.marketing_db.close()
  336. self.linshi_db.close()
  337. def init_city(self):
  338. """
  339. 获取答题数据中的城市。
  340. :return:
  341. """
  342. citys = ['上海市', '上海周边']
  343. # citys_info = self.marketing_db.select(self.sql_1)
  344. # citys.extend([x[0] for x in citys_info if x[0] is not None])
  345. return citys
  346. def query_behavioral_info(self, city=None, age=None, crowd=None):
  347. """
  348. 查询行为兴趣信息
  349. :return:
  350. """
  351. # datas = []
  352. # for key in self.tag_data.keys():
  353. # values = self.tag_data[key]
  354. # for value in values:
  355. # question = value[0].split('-')[0]
  356. # option = value[0].split('-')[1]
  357. # corr = value[1]
  358. # data = self.shangju_db.select(self.sql_2, [option, question])
  359. # if len(data) > 0:
  360. # print([question, option, data[0][3], data[0][1], key, corr])
  361. # datas.append([question, option, data[0][3], data[0][1], key, corr])
  362. # self.shangju_db.truncate('mvp_question_classification')
  363. # self.shangju_db.add_some(self.sql_3, datas)
  364. scores_behavioral = self.city_age_crowd(city, age, crowd)
  365. # scores_module = self.module_score(crowd, city, age, scores_behavioral['score'])
  366. # result = {'行为兴趣分值': scores_behavioral['score'], '模块分值': scores_module}
  367. print('update finished!!!')
  368. return scores_behavioral
  369. def people_info(self):
  370. """
  371. 答题人个人信息获取
  372. :return:
  373. """
  374. people_info_city = self.marketing_db.select(self.sql_15)
  375. people_infos = []
  376. for people in people_info_city:
  377. uuid = people[0]
  378. city = people[1]
  379. nld = people[2]
  380. sex = people[3]
  381. if sex and len(str(sex).split(',')) > 0:
  382. sex = str(sex).split(',')[0]
  383. else:
  384. sex = '3'
  385. sub_option_ids_1 = people[4]
  386. testcaseid = people[5]
  387. if str(city).find('市') != -1:
  388. city = str(city).split('市')[0] + '市'
  389. if str(nld).find(',') != -1:
  390. nld_1 = list(str(nld).split(','))
  391. if len(nld_1) > 0:
  392. nld = nld_1[0]
  393. else:
  394. pass
  395. crowd = []
  396. if testcaseid:
  397. testcastids = list(map(int, str(testcaseid).split(',')))
  398. if len(testcastids) > 0:
  399. gt_75 = [x for x in testcastids if x > 74]
  400. if len(gt_75) > 0:
  401. # 从答题结果中获取城市信息
  402. citys = self.marketing_db.select(self.sql_16, [uuid])
  403. if len(citys) > 0:
  404. if citys[0][1] in ('上海市', '一线', '上海', '北京', '广州', '深圳', '北京市', '广州市', '深圳市'):
  405. city = '上海市'
  406. # elif citys[0][1] in ('二线', '杭州', '宁波', '无锡', '苏州', '杭州市', '宁波市', '无锡市', '苏州市'):
  407. # city = '上海周边'
  408. else:
  409. city = '上海周边'
  410. # city = '上海市' if (citys[0][1] == '一线' or citys[0][1] == '上海') else '上海周边'
  411. # 根据用户子选项id集合,获取用户的人群分类
  412. if len(gt_75) > 0:
  413. # 特定的测试人群分类从答题结果中获取
  414. sub_option_ids = self.marketing_db.select(self.sql_17, [uuid])
  415. for option in sub_option_ids:
  416. crowd_type = self.crowd_info_1.get(option[1])
  417. if crowd_type:
  418. crowd.append(crowd_type)
  419. else:
  420. crowd.append('A')
  421. else:
  422. if sub_option_ids_1 is not None:
  423. crowd.extend(self.get_people_uuid_by_sub_option_ids(sub_option_ids_1))
  424. if city is None:
  425. city = '上海市'
  426. people_info = PeopleInfo(uuid, city, nld, sex, crowd)
  427. people_infos.append(people_info)
  428. # people_infos.append([uuid, city, nld, sex, crowd])
  429. return people_infos
  430. def people_filter(self, city, nld, crowd):
  431. uuids = []
  432. for people in self.people_info_1:
  433. if people.city == city and people.age == nld and crowd in people.crowd:
  434. uuids.append(people.uuid)
  435. return uuids
  436. def get_people_uuid_by_sub_option_ids(self, sub_ids):
  437. types = []
  438. for key in self.crowd_contain_sub_option_ids.keys():
  439. type_sub_option_ids = self.crowd_contain_sub_option_ids[key]
  440. sub_option_ids = list(map(int, str(sub_ids).split(',')))
  441. # list(set(a).intersection(set(b)))
  442. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and key not in types:
  443. types.append(key)
  444. return types
  445. def update_data(self):
  446. """
  447. 定时更新分值
  448. 使用真实数据模块名称:空间需求图谱-材质,空间需求图谱-色调,空间需求图谱-色相
  449. 用户画像-行业,用户画像-出行方式,用户画像-消费结构,用户画像-生活方式,用户画像-社交模式, 模块分数
  450. :return:
  451. """
  452. message = {}
  453. try:
  454. self.insert_table = []
  455. self.ids = self.query_data()
  456. for city in self.city_list:
  457. for age in self.age_list:
  458. for crowd in self.crowd:
  459. result = self.city_age_crowd(city, age, crowd)
  460. self.insert_score_to_db(result)
  461. self.linshi_db.delete(self.sql_18)
  462. message['实际分值'] = '更新完成'
  463. # insert_data = self.shanghai_85_module_score_insert()
  464. self.linshi_db.delete(self.sql_23)
  465. # self.insert_score_to_db(insert_data)
  466. message['模块模拟分值'] = '更新完成'
  467. self.update_gender_rate()
  468. message['性别信息'] = '更新完成'
  469. self.update_icon()
  470. message['行为图标'] = '更新完成'
  471. return message
  472. except Exception as e:
  473. message['error'] = str(e)
  474. return message
  475. def update_gender_rate(self, ids=None):
  476. """
  477. 更新性别占比
  478. :return:
  479. """
  480. if ids:
  481. self.ids = self.query_data()
  482. insert_data = []
  483. for city in self.city_list:
  484. for age in self.age_list:
  485. for crowd in self.crowd:
  486. boy = 0
  487. girl = 0
  488. for people in self.people_info_1:
  489. if people.sex is not None and city == people.city and crowd in people.crowd and age == people.age:
  490. if people.sex == '1':
  491. boy += 1
  492. if people.sex == '2':
  493. girl += 1
  494. crowd_info_id = self.get_crowd_info_id([city, age, crowd])
  495. if crowd_info_id and (boy + girl) > 0:
  496. boy_rate = boy / (boy + girl)
  497. insert_data.append([crowd_info_id, 1, boy_rate])
  498. girl_rate = girl / (boy + girl)
  499. insert_data.append([crowd_info_id, 0, girl_rate])
  500. if len(insert_data) > 0:
  501. self.linshi_db.truncate('mvp_crowd_info_gender_rate')
  502. self.linshi_db.add_some(self.sql_22, insert_data)
  503. print('性别占比更新完成...')
  504. else:
  505. print('无数据更新...')
  506. def get_crowd_info_id(self, people_info):
  507. for id_data in self.ids:
  508. city_1 = id_data[2]
  509. age_1 = id_data[1]
  510. crowd_1 = id_data[3]
  511. id_1 = id_data[0]
  512. if people_info[0] == city_1 and people_info[1] == age_1 and people_info[2] == crowd_1:
  513. return id_1
  514. def update_image(self):
  515. """
  516. 更新标签关联的图片信息
  517. :return:
  518. """
  519. pass
  520. def update_icon(self):
  521. """
  522. 标签关联图标
  523. :return:
  524. """
  525. icons = self.linshi_db.select(self.sql_19)
  526. for ic in icons:
  527. id = ic[0]
  528. name = ic[1]
  529. self.linshi_db.update(self.sql_20, [id, name])
  530. print('行为标签关联图标完成...')
  531. def insert_score_to_db(self, scores):
  532. """
  533. 行为、模块分数写入数据库
  534. :return:
  535. """
  536. behavior_score = scores['behavior_score']
  537. module_score = scores['module_score']
  538. module_insert_sql = self.get_insert_sql('模块分数')
  539. if module_insert_sql:
  540. module_insert_data = []
  541. for module in module_score:
  542. data = self.need_inert(module)
  543. if data:
  544. module_insert_data.append(data)
  545. # 先清空之前的数据
  546. if len(module_insert_data) > 0:
  547. table_name = self.get_table_name('模块分数')
  548. if table_name is not None and table_name not in self.insert_table:
  549. # self.linshi_db.delete(self.sql_23)
  550. self.linshi_db.truncate(table_name)
  551. self.linshi_db.add_some(module_insert_sql, module_insert_data)
  552. self.insert_table.append(table_name)
  553. print('模块分数更新完成...')
  554. for b_score in behavior_score:
  555. for key in b_score.keys():
  556. insert_sql = self.get_insert_sql(key)
  557. if insert_sql:
  558. insert_data = []
  559. score = b_score[key]
  560. for data in score:
  561. insert_data_element = self.need_inert(data)
  562. if insert_data_element:
  563. insert_data.append(insert_data_element)
  564. if len(insert_data) > 0:
  565. table_name = self.get_table_name(key)
  566. if table_name and table_name not in self.insert_table:
  567. # if table_name == 'mvp_crowd_info_behavior':
  568. # self.linshi_db.delete(self.sql_18)
  569. # else:
  570. self.linshi_db.truncate(table_name)
  571. self.linshi_db.add_some(insert_sql, insert_data)
  572. self.insert_table.append(table_name)
  573. else:
  574. print('未找到对应的表,数据无法插入...')
  575. print('行为分数更新完成...')
  576. def need_inert(self, data):
  577. city = data[0]
  578. age = data[1]
  579. crowd = data[2]
  580. tag_name = data[3]
  581. tag_score = data[4]
  582. # if key == '用户画像-行为兴趣' and city == '上海市' and age == '85后':
  583. # pass
  584. # else:
  585. for id_data in self.ids:
  586. city_1 = id_data[2]
  587. age_1 = id_data[1]
  588. crowd_1 = id_data[3]
  589. id_1 = id_data[0]
  590. if city == city_1 and age == age_1 and crowd == crowd_1:
  591. return [id_1, tag_name, tag_score]
  592. def module_score(self, crowd, city, age, scores):
  593. """
  594. 模块分数计算
  595. 城市 年龄 人群分类 模块名称 分数
  596. :return:
  597. """
  598. # import json
  599. # print(json.dumps(scores, ensure_ascii=False))
  600. modules = self.module_scores
  601. result = []
  602. for key in modules.keys():
  603. values = modules[key]
  604. module_name = key
  605. score = 0
  606. for value in values:
  607. behavioral_name = value[0]
  608. weight = float(value[1])
  609. standard_score = [x[4] for x in scores if x[3] == behavioral_name]
  610. if len(standard_score) > 0:
  611. score += standard_score[0] * weight
  612. score = 1 if score > 1 else score
  613. result.append([city, age, crowd, module_name, score])
  614. return result
  615. # def insert_data(self, scores_behavioral, scores_module):
  616. def insert(self):
  617. """
  618. 计算数据写入数据库中,供接口查看
  619. :return:
  620. """
  621. infos = []
  622. for city in self.city_list:
  623. for age in self.age_list:
  624. for c_type in self.crowd:
  625. age_area = self.age_dict.get(age)
  626. if age_area:
  627. infos.append([age_area, city, c_type])
  628. self.shangju_db.add_some(self.sql_11, infos)
  629. def query_data(self):
  630. ids = self.linshi_db.select(self.sql_14)
  631. return ids
  632. def shanghai_85_module_score_insert(self):
  633. """
  634. 上海市,85后模块分数计算
  635. :return:
  636. """
  637. result = []
  638. for crowd in self.crowd:
  639. modules = self.module_scores[crowd]
  640. for key in modules.keys():
  641. values = modules[key]
  642. module_name = key
  643. score = 0
  644. for value in values:
  645. # behavioral_name = value[0]
  646. weight = float(value[2])
  647. # standard_score = [x[4] for x in scores if x[2] == behavioral_name]
  648. standard_score = float(value[1])
  649. if standard_score is not None:
  650. score += standard_score*random.uniform(0.8, 1.2) * weight
  651. result.append(['上海市', '85后', crowd, module_name, score])
  652. # return result
  653. return {'behavior_score': [], 'module_score': result}
  654. def init_age(self):
  655. """
  656. 获取答题数据中的年龄
  657. """
  658. return ['95后', '85后']
  659. # age_info = self.marketing_db.select(self.sql_4)
  660. # # print([x[0] for x in age_info])
  661. # return [x[0] for x in age_info if x[0] is not None]
  662. def city_age_crowd(self, city=None, age=None, crowd=None):
  663. data_start = []
  664. result = []
  665. module_scores = []
  666. if city is not None and age is not None and crowd is not None:
  667. print('获取指定城市,年龄段,人群类型的数据...')
  668. # people_uuids = self.get_people_uuid_by_type(crowd)
  669. people_uuids = self.people_filter(city, age, crowd)
  670. behavior_data = None
  671. if len(people_uuids) > 0:
  672. print('{}-{}-{}'.format(city, age, crowd))
  673. datas = self.behavior_tag_init(city, age, people_uuids)
  674. data_start.append(datas)
  675. all_data, behavior_data_1 = self.calculation_standard_score(datas, city, age, crowd)
  676. result.append(all_data)
  677. behavior_data = behavior_data_1
  678. if behavior_data:
  679. module_scores.extend(self.module_score(crowd, city, age, behavior_data))
  680. # data_list = []
  681. # for e in data_start:
  682. # for key in e.keys():
  683. # values = e[key]
  684. # for sub_e in values:
  685. # ele = [key]
  686. # ele.extend(sub_e)
  687. # data_list.append(ele)
  688. # pass
  689. return {'behavior_score': result, 'module_score': module_scores}
  690. # return {'score': result, 'data': data_list}
  691. def scores(self):
  692. behavior_score = []
  693. module_scores = []
  694. for city in self.city_list:
  695. for age in self.age_list:
  696. for crowd in self.crowd:
  697. data = self.city_age_crowd(city, age, crowd)
  698. behavior_score.extend(data['behavior_score'])
  699. module_scores.extend(data['module_score'])
  700. return {'behavior_score': behavior_score, 'module_score': module_scores}
  701. def behavior_tag_init(self, city, age, people_uuids):
  702. result = {}
  703. self.group_type_count = self.marketing_db.select(self.sql_5, [people_uuids])
  704. # 表名
  705. for key in self.tag_data.keys():
  706. values = self.tag_data[key]
  707. result_sub = {}
  708. for key_tag_name in values.keys():
  709. questions = values[key_tag_name]
  710. elements = []
  711. for value in questions:
  712. question = value[0].split('-')[0]
  713. option = value[0].split('-')[1]
  714. corr = value[1]
  715. fz, fm = self.molecular_value(question, option, city, age, people_uuids)
  716. if fm == 0:
  717. c = 0
  718. else:
  719. c = fz / fm
  720. elements.append([question, option, corr, fz, fm, c])
  721. result_sub[key_tag_name] = elements
  722. result[key] = self.indicator_calculation_d_e(result_sub)
  723. return result
  724. def molecular_value(self, queston, option, city, age, people_uuids):
  725. # 获取当前父选项包含的子选项id和子题id列表
  726. result = self.shangju_db.select(self.sql_6, [option, queston])
  727. sub_option_ids = []
  728. group_types = []
  729. for rt in result:
  730. sub_option_id, sub_question_id, content = rt[0], rt[1], rt[2]
  731. grouptypes = self.shangju_db.select(self.sql_7, [sub_question_id])
  732. for g_t in grouptypes:
  733. if str(g_t[0]) not in group_types:
  734. group_types.append(str(g_t[0]))
  735. sub_option_ids.append(sub_option_id)
  736. # 计算子选项在答题记录中的点击数
  737. sub_options_count = 0
  738. if len(sub_option_ids) > 0:
  739. result_1 = self.marketing_db.select(self.sql_8, [sub_option_ids, people_uuids])
  740. sub_options_count = result_1[0][0]
  741. # 计算父选项包含的子选项对应的子题所在的测试gt包含的点击数。
  742. denominator_value = 0
  743. for info in self.group_type_count:
  744. if str(info[0]) in group_types:
  745. denominator_value += info[1]
  746. return sub_options_count, denominator_value
  747. def indicator_calculation_d_e(self, data):
  748. result = {}
  749. for key in data.keys():
  750. values = data[key]
  751. c_list = []
  752. for x in values:
  753. _x = x[5]
  754. if _x is not None and x != 0:
  755. c_list.append(_x)
  756. fm_list = [x[4] for x in values]
  757. sum_c = sum(fm_list)
  758. if len(c_list) == 0:
  759. min_c = 0
  760. else:
  761. min_c = min(c_list)
  762. elements = []
  763. for value in values:
  764. _value = []
  765. c = value[5]
  766. if sum_c == 0:
  767. d = 0
  768. else:
  769. d = c / sum_c
  770. e = c - min_c
  771. _value.extend(value)
  772. _value.append(d)
  773. _value.append(e)
  774. elements.append(_value)
  775. result[key] = elements
  776. return result
  777. def calculation_standard_score(self, datas, city, age, crowd_type):
  778. scores = {}
  779. for key_tag_type in datas.keys():
  780. print(key_tag_type)
  781. tag_type_data = datas[key_tag_type]
  782. scores_sub = []
  783. for key_tag in tag_type_data.keys():
  784. key_tag_data = tag_type_data[key_tag]
  785. print(key_tag)
  786. print(' 父题序号 父选项序号 相关系系数 分子值 分母值 百分比 人数权重 偏离值')
  787. values = [x[5] for x in key_tag_data]
  788. min_c = min(values)
  789. f = min_c
  790. for value in key_tag_data:
  791. print(' {}'.format(value))
  792. if value[2] is not None and value[7] is not None:
  793. f += float(value[2] * value[7])
  794. print(' 标准分:{}'.format(f))
  795. if key_tag_type == '用户画像-行为兴趣':
  796. f = f * random.uniform(0.8, 1.2)
  797. scores_sub.append([city, age, crowd_type, key_tag, f])
  798. scores[key_tag_type] = scores_sub
  799. # self.shangju_db.add_some(self.sql_9, scores)
  800. return scores, scores['用户画像-行为兴趣']
  801. def people_data(self):
  802. result = self.people_info()
  803. a = 0
  804. b = 0
  805. c = 0
  806. d = 0
  807. e = 0
  808. f = 0
  809. for rt in result:
  810. crowds = rt.crowd
  811. if 'A' in crowds:
  812. a += 1
  813. if 'B' in crowds:
  814. b += 1
  815. if 'C' in crowds:
  816. c += 1
  817. if 'D' in crowds:
  818. d += 1
  819. if 'E' in crowds:
  820. e += 1
  821. if 'F' in crowds:
  822. f += 1
  823. return {'A': a, 'B': b, 'C': b, 'D': d, 'E': e, 'F': f}
  824. def get_crowd_people(self):
  825. result = {}
  826. for type in self.crowd:
  827. uuids = self.get_people_uuid_by_type(type)
  828. result[type] = len(uuids)
  829. return result
  830. def get_people_uuid_by_type(self, type):
  831. uuids = []
  832. type_sub_option_ids = self.crowd_contain_sub_option_ids[type]
  833. for people in self.people_sub_option_ids:
  834. uuid = people[0]
  835. sub_option_ids = list(map(int, str(people[1]).split(',')))
  836. # list(set(a).intersection(set(b)))
  837. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and uuid not in uuids:
  838. uuids.append(uuid)
  839. return uuids
  840. def get_crowd_contain_sub_option_ids(self):
  841. """
  842. 获取ABCDEF人群包含的子选项id
  843. :return:
  844. """
  845. infos = {}
  846. for key in self.crowd_info.keys():
  847. values = self.crowd_info[key]
  848. sub_option_ids = []
  849. for value in values:
  850. if value is not None:
  851. vals = str(value).split('-')
  852. option, question = vals[1], vals[0]
  853. query_result = self.shangju_db.select(self.sql_6, [option, question])
  854. for qr in query_result:
  855. sub_option_id, sub_question_id, content = qr[0], qr[1], qr[2]
  856. sub_option_ids.append(int(sub_option_id))
  857. infos[key] = sub_option_ids
  858. return infos
  859. if __name__ == '__main__':
  860. pass