mvp.py 33 KB

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