mvp.py 38 KB

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