mvp.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. city = '上海市' if (citys[0][1] == '一线' or citys[0][1] == '上海') else '上海周边'
  405. # 根据用户子选项id集合,获取用户的人群分类
  406. if len(gt_75) > 0:
  407. # 特定的测试人群分类从答题结果中获取
  408. sub_option_ids = self.marketing_db.select(self.sql_17, [uuid])
  409. for option in sub_option_ids:
  410. crowd_type = self.crowd_info_1.get(option[1])
  411. if crowd_type:
  412. crowd.append(crowd_type)
  413. else:
  414. crowd.append('A')
  415. else:
  416. if sub_option_ids_1 is not None:
  417. crowd.extend(self.get_people_uuid_by_sub_option_ids(sub_option_ids_1))
  418. if city is None:
  419. city = '上海市'
  420. people_info = PeopleInfo(uuid, city, nld, sex, crowd)
  421. people_infos.append(people_info)
  422. # people_infos.append([uuid, city, nld, sex, crowd])
  423. return people_infos
  424. def people_filter(self, city, nld, crowd):
  425. uuids = []
  426. for people in self.people_info_1:
  427. if people.city == city and people.age == nld and crowd in people.crowd:
  428. uuids.append(people.uuid)
  429. return uuids
  430. def get_people_uuid_by_sub_option_ids(self, sub_ids):
  431. types = []
  432. for key in self.crowd_contain_sub_option_ids.keys():
  433. type_sub_option_ids = self.crowd_contain_sub_option_ids[key]
  434. sub_option_ids = list(map(int, str(sub_ids).split(',')))
  435. # list(set(a).intersection(set(b)))
  436. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and key not in types:
  437. types.append(key)
  438. return types
  439. def update_data(self):
  440. """
  441. 定时更新分值
  442. 使用真实数据模块名称:空间需求图谱-材质,空间需求图谱-色调,空间需求图谱-色相
  443. 用户画像-行业,用户画像-出行方式,用户画像-消费结构,用户画像-生活方式,用户画像-社交模式, 模块分数
  444. :return:
  445. """
  446. message = {}
  447. try:
  448. self.insert_table = []
  449. self.ids = self.query_data()
  450. for city in self.city_list:
  451. for age in self.age_list:
  452. for crowd in self.crowd:
  453. result = self.city_age_crowd(city, age, crowd)
  454. self.insert_score_to_db(result)
  455. self.linshi_db.delete(self.sql_18)
  456. message['实际分值'] = '更新完成'
  457. # insert_data = self.shanghai_85_module_score_insert()
  458. self.linshi_db.delete(self.sql_23)
  459. # self.insert_score_to_db(insert_data)
  460. message['模块模拟分值'] = '更新完成'
  461. self.update_gender_rate()
  462. message['性别信息'] = '更新完成'
  463. self.update_icon()
  464. message['行为图标'] = '更新完成'
  465. return message
  466. except Exception as e:
  467. message['error'] = str(e)
  468. return message
  469. def update_gender_rate(self, ids=None):
  470. """
  471. 更新性别占比
  472. :return:
  473. """
  474. if ids:
  475. self.ids = self.query_data()
  476. insert_data = []
  477. for city in self.city_list:
  478. for age in self.age_list:
  479. for crowd in self.crowd:
  480. boy = 0
  481. girl = 0
  482. for people in self.people_info_1:
  483. if people.sex is not None and city == people.city and crowd in people.crowd and age == people.age:
  484. if people.sex == '1':
  485. boy += 1
  486. if people.sex == '2':
  487. girl += 1
  488. crowd_info_id = self.get_crowd_info_id([city, age, crowd])
  489. if crowd_info_id and (boy + girl) > 0:
  490. boy_rate = boy / (boy + girl)
  491. insert_data.append([crowd_info_id, 1, boy_rate])
  492. girl_rate = girl / (boy + girl)
  493. insert_data.append([crowd_info_id, 0, girl_rate])
  494. if len(insert_data) > 0:
  495. self.linshi_db.truncate('mvp_crowd_info_gender_rate')
  496. self.linshi_db.add_some(self.sql_22, insert_data)
  497. print('性别占比更新完成...')
  498. else:
  499. print('无数据更新...')
  500. def get_crowd_info_id(self, people_info):
  501. for id_data in self.ids:
  502. city_1 = id_data[2]
  503. age_1 = id_data[1]
  504. crowd_1 = id_data[3]
  505. id_1 = id_data[0]
  506. if people_info[0] == city_1 and people_info[1] == age_1 and people_info[2] == crowd_1:
  507. return id_1
  508. def update_image(self):
  509. """
  510. 更新标签关联的图片信息
  511. :return:
  512. """
  513. pass
  514. def update_icon(self):
  515. """
  516. 标签关联图标
  517. :return:
  518. """
  519. icons = self.linshi_db.select(self.sql_19)
  520. for ic in icons:
  521. id = ic[0]
  522. name = ic[1]
  523. self.linshi_db.update(self.sql_20, [id, name])
  524. print('行为标签关联图标完成...')
  525. def insert_score_to_db(self, scores):
  526. """
  527. 行为、模块分数写入数据库
  528. :return:
  529. """
  530. behavior_score = scores['behavior_score']
  531. module_score = scores['module_score']
  532. module_insert_sql = self.get_insert_sql('模块分数')
  533. if module_insert_sql:
  534. module_insert_data = []
  535. for module in module_score:
  536. data = self.need_inert(module)
  537. if data:
  538. module_insert_data.append(data)
  539. # 先清空之前的数据
  540. if len(module_insert_data) > 0:
  541. table_name = self.get_table_name('模块分数')
  542. if table_name is not None and table_name not in self.insert_table:
  543. # self.linshi_db.delete(self.sql_23)
  544. self.linshi_db.truncate(table_name)
  545. self.linshi_db.add_some(module_insert_sql, module_insert_data)
  546. self.insert_table.append(table_name)
  547. print('模块分数更新完成...')
  548. for b_score in behavior_score:
  549. for key in b_score.keys():
  550. insert_sql = self.get_insert_sql(key)
  551. if insert_sql:
  552. insert_data = []
  553. score = b_score[key]
  554. for data in score:
  555. insert_data_element = self.need_inert(data)
  556. if insert_data_element:
  557. insert_data.append(insert_data_element)
  558. if len(insert_data) > 0:
  559. table_name = self.get_table_name(key)
  560. if table_name and table_name not in self.insert_table:
  561. # if table_name == 'mvp_crowd_info_behavior':
  562. # self.linshi_db.delete(self.sql_18)
  563. # else:
  564. self.linshi_db.truncate(table_name)
  565. self.linshi_db.add_some(insert_sql, insert_data)
  566. self.insert_table.append(table_name)
  567. else:
  568. print('未找到对应的表,数据无法插入...')
  569. print('行为分数更新完成...')
  570. def need_inert(self, data):
  571. city = data[0]
  572. age = data[1]
  573. crowd = data[2]
  574. tag_name = data[3]
  575. tag_score = data[4]
  576. # if key == '用户画像-行为兴趣' and city == '上海市' and age == '85后':
  577. # pass
  578. # else:
  579. for id_data in self.ids:
  580. city_1 = id_data[2]
  581. age_1 = id_data[1]
  582. crowd_1 = id_data[3]
  583. id_1 = id_data[0]
  584. if city == city_1 and age == age_1 and crowd == crowd_1:
  585. return [id_1, tag_name, tag_score]
  586. def module_score(self, crowd, city, age, scores):
  587. """
  588. 模块分数计算
  589. 城市 年龄 人群分类 模块名称 分数
  590. :return:
  591. """
  592. # import json
  593. # print(json.dumps(scores, ensure_ascii=False))
  594. modules = self.module_scores
  595. result = []
  596. for key in modules.keys():
  597. values = modules[key]
  598. module_name = key
  599. score = 0
  600. for value in values:
  601. behavioral_name = value[0]
  602. weight = float(value[1])
  603. standard_score = [x[4] for x in scores if x[3] == behavioral_name]
  604. if len(standard_score) > 0:
  605. score += standard_score[0] * weight
  606. score = 1 if score > 1 else score
  607. result.append([city, age, crowd, module_name, score])
  608. return result
  609. # def insert_data(self, scores_behavioral, scores_module):
  610. def insert(self):
  611. """
  612. 计算数据写入数据库中,供接口查看
  613. :return:
  614. """
  615. infos = []
  616. for city in self.city_list:
  617. for age in self.age_list:
  618. for c_type in self.crowd:
  619. age_area = self.age_dict.get(age)
  620. if age_area:
  621. infos.append([age_area, city, c_type])
  622. self.shangju_db.add_some(self.sql_11, infos)
  623. def query_data(self):
  624. ids = self.linshi_db.select(self.sql_14)
  625. return ids
  626. def shanghai_85_module_score_insert(self):
  627. """
  628. 上海市,85后模块分数计算
  629. :return:
  630. """
  631. result = []
  632. for crowd in self.crowd:
  633. modules = self.module_scores[crowd]
  634. for key in modules.keys():
  635. values = modules[key]
  636. module_name = key
  637. score = 0
  638. for value in values:
  639. # behavioral_name = value[0]
  640. weight = float(value[2])
  641. # standard_score = [x[4] for x in scores if x[2] == behavioral_name]
  642. standard_score = float(value[1])
  643. if standard_score is not None:
  644. score += standard_score*random.uniform(0.8, 1.2) * weight
  645. result.append(['上海市', '85后', crowd, module_name, score])
  646. # return result
  647. return {'behavior_score': [], 'module_score': result}
  648. def init_age(self):
  649. """
  650. 获取答题数据中的年龄
  651. """
  652. return ['95后', '85后']
  653. # age_info = self.marketing_db.select(self.sql_4)
  654. # # print([x[0] for x in age_info])
  655. # return [x[0] for x in age_info if x[0] is not None]
  656. def city_age_crowd(self, city=None, age=None, crowd=None):
  657. data_start = []
  658. result = []
  659. module_scores = []
  660. if city is not None and age is not None and crowd is not None:
  661. print('获取指定城市,年龄段,人群类型的数据...')
  662. # people_uuids = self.get_people_uuid_by_type(crowd)
  663. people_uuids = self.people_filter(city, age, crowd)
  664. behavior_data = None
  665. if len(people_uuids) > 0:
  666. print('{}-{}-{}'.format(city, age, crowd))
  667. datas = self.behavior_tag_init(city, age, people_uuids)
  668. data_start.append(datas)
  669. all_data, behavior_data_1 = self.calculation_standard_score(datas, city, age, crowd)
  670. result.append(all_data)
  671. behavior_data = behavior_data_1
  672. if behavior_data:
  673. module_scores.extend(self.module_score(crowd, city, age, behavior_data))
  674. # data_list = []
  675. # for e in data_start:
  676. # for key in e.keys():
  677. # values = e[key]
  678. # for sub_e in values:
  679. # ele = [key]
  680. # ele.extend(sub_e)
  681. # data_list.append(ele)
  682. # pass
  683. return {'behavior_score': result, 'module_score': module_scores}
  684. # return {'score': result, 'data': data_list}
  685. def scores(self):
  686. behavior_score = []
  687. module_scores = []
  688. for city in self.city_list:
  689. for age in self.age_list:
  690. for crowd in self.crowd:
  691. data = self.city_age_crowd(city, age, crowd)
  692. behavior_score.extend(data['behavior_score'])
  693. module_scores.extend(data['module_score'])
  694. return {'behavior_score': behavior_score, 'module_score': module_scores}
  695. def behavior_tag_init(self, city, age, people_uuids):
  696. result = {}
  697. self.group_type_count = self.marketing_db.select(self.sql_5, [people_uuids])
  698. # 表名
  699. for key in self.tag_data.keys():
  700. values = self.tag_data[key]
  701. result_sub = {}
  702. for key_tag_name in values.keys():
  703. questions = values[key_tag_name]
  704. elements = []
  705. for value in questions:
  706. question = value[0].split('-')[0]
  707. option = value[0].split('-')[1]
  708. corr = value[1]
  709. fz, fm = self.molecular_value(question, option, city, age, people_uuids)
  710. if fm == 0:
  711. c = 0
  712. else:
  713. c = fz / fm
  714. elements.append([question, option, corr, fz, fm, c])
  715. result_sub[key_tag_name] = elements
  716. result[key] = self.indicator_calculation_d_e(result_sub)
  717. return result
  718. def molecular_value(self, queston, option, city, age, people_uuids):
  719. # 获取当前父选项包含的子选项id和子题id列表
  720. result = self.shangju_db.select(self.sql_6, [option, queston])
  721. sub_option_ids = []
  722. group_types = []
  723. for rt in result:
  724. sub_option_id, sub_question_id, content = rt[0], rt[1], rt[2]
  725. grouptypes = self.shangju_db.select(self.sql_7, [sub_question_id])
  726. for g_t in grouptypes:
  727. if str(g_t[0]) not in group_types:
  728. group_types.append(str(g_t[0]))
  729. sub_option_ids.append(sub_option_id)
  730. # 计算子选项在答题记录中的点击数
  731. sub_options_count = 0
  732. if len(sub_option_ids) > 0:
  733. result_1 = self.marketing_db.select(self.sql_8, [sub_option_ids, people_uuids])
  734. sub_options_count = result_1[0][0]
  735. # 计算父选项包含的子选项对应的子题所在的测试gt包含的点击数。
  736. denominator_value = 0
  737. for info in self.group_type_count:
  738. if str(info[0]) in group_types:
  739. denominator_value += info[1]
  740. return sub_options_count, denominator_value
  741. def indicator_calculation_d_e(self, data):
  742. result = {}
  743. for key in data.keys():
  744. values = data[key]
  745. c_list = []
  746. for x in values:
  747. _x = x[5]
  748. if _x is not None and x != 0:
  749. c_list.append(_x)
  750. fm_list = [x[4] for x in values]
  751. sum_c = sum(fm_list)
  752. if len(c_list) == 0:
  753. min_c = 0
  754. else:
  755. min_c = min(c_list)
  756. elements = []
  757. for value in values:
  758. _value = []
  759. c = value[5]
  760. if sum_c == 0:
  761. d = 0
  762. else:
  763. d = c / sum_c
  764. e = c - min_c
  765. _value.extend(value)
  766. _value.append(d)
  767. _value.append(e)
  768. elements.append(_value)
  769. result[key] = elements
  770. return result
  771. def calculation_standard_score(self, datas, city, age, crowd_type):
  772. scores = {}
  773. for key_tag_type in datas.keys():
  774. print(key_tag_type)
  775. tag_type_data = datas[key_tag_type]
  776. scores_sub = []
  777. for key_tag in tag_type_data.keys():
  778. key_tag_data = tag_type_data[key_tag]
  779. print(key_tag)
  780. print(' 父题序号 父选项序号 相关系系数 分子值 分母值 百分比 人数权重 偏离值')
  781. values = [x[5] for x in key_tag_data]
  782. min_c = min(values)
  783. f = min_c
  784. for value in key_tag_data:
  785. print(' {}'.format(value))
  786. if value[2] is not None and value[7] is not None:
  787. f += float(value[2] * value[7])
  788. print(' 标准分:{}'.format(f))
  789. if key_tag_type == '用户画像-行为兴趣':
  790. f = f * random.uniform(0.8, 1.2)
  791. scores_sub.append([city, age, crowd_type, key_tag, f])
  792. scores[key_tag_type] = scores_sub
  793. # self.shangju_db.add_some(self.sql_9, scores)
  794. return scores, scores['用户画像-行为兴趣']
  795. def people_data(self):
  796. result = self.people_info()
  797. a = 0
  798. b = 0
  799. c = 0
  800. d = 0
  801. e = 0
  802. f = 0
  803. for rt in result:
  804. crowds = rt.crowd
  805. if 'A' in crowds:
  806. a += 1
  807. if 'B' in crowds:
  808. b += 1
  809. if 'C' in crowds:
  810. c += 1
  811. if 'D' in crowds:
  812. d += 1
  813. if 'E' in crowds:
  814. e += 1
  815. if 'F' in crowds:
  816. f += 1
  817. return {'A': a, 'B': b, 'C': b, 'D': d, 'E': e, 'F': f}
  818. def get_crowd_people(self):
  819. result = {}
  820. for type in self.crowd:
  821. uuids = self.get_people_uuid_by_type(type)
  822. result[type] = len(uuids)
  823. return result
  824. def get_people_uuid_by_type(self, type):
  825. uuids = []
  826. type_sub_option_ids = self.crowd_contain_sub_option_ids[type]
  827. for people in self.people_sub_option_ids:
  828. uuid = people[0]
  829. sub_option_ids = list(map(int, str(people[1]).split(',')))
  830. # list(set(a).intersection(set(b)))
  831. if len(list(set(sub_option_ids).intersection(set(type_sub_option_ids)))) > 0 and uuid not in uuids:
  832. uuids.append(uuid)
  833. return uuids
  834. def get_crowd_contain_sub_option_ids(self):
  835. """
  836. 获取ABCDEF人群包含的子选项id
  837. :return:
  838. """
  839. infos = {}
  840. for key in self.crowd_info.keys():
  841. values = self.crowd_info[key]
  842. sub_option_ids = []
  843. for value in values:
  844. if value is not None:
  845. vals = str(value).split('-')
  846. option, question = vals[1], vals[0]
  847. query_result = self.shangju_db.select(self.sql_6, [option, question])
  848. for qr in query_result:
  849. sub_option_id, sub_question_id, content = qr[0], qr[1], qr[2]
  850. sub_option_ids.append(int(sub_option_id))
  851. infos[key] = sub_option_ids
  852. return infos
  853. if __name__ == '__main__':
  854. pass