mvp.py 33 KB

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