mvp.py 38 KB

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