mvp.py 36 KB

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