def message(mes): space = db['space'].find_one({'id': mes['space']}) timestamp = time.time() message_id = next_id('space') space['messages'].append({ 'id': message_id, 'user': mes['token'], 'cont': mes['cont'], 'time': timestamp, }) db['space'].save(space) # Отправить сообщение sio.emit('message_get', { 'space': mes['space'], 'id': message_id, 'user': mes['token'], 'cont': mes['cont'], 'time': timestamp, }, namespace='/main')
def edit(this, **x): # Проверка параметров # Редактирование if 'id' in x: check_params(x, ( ('id', True, int), ('image', False, str, True), ('text', False, str, True), ('tags', False, list, str, True), )) # Добавление else: check_params(x, ( ('image', False, str, True), ('file', False, str, True), ('text', False, str, True), ('tags', False, list, str, True), )) # Не авторизован if this.user['admin'] < 3: raise ErrorAccess('add / edit') # Редактирование if 'id' in x: query = db['tasks'].find_one({'id': x['id']}) # Неправильный id if not query: raise ErrorWrong('tasks') # Чужое задание if query['token'] != this.user['token']: raise ErrorAccess('token') process_edit = True # Создание else: # Нет содержимого cond_text = 'text' not in x or not x['text'] cond_img = 'image' not in x or not x['image'] if cond_text and cond_img: raise ErrorInvalid('image / text') # query = { 'id': next_id('tasks'), 'time': this.timestamp, 'text': x['text'] if 'text' in x else '', 'tags': x['tags'] if 'tags' in x else [], 'user': this.user['token'], } process_edit = False # Загрузка картинки if 'image' in x: try: file_type = x['file'].split('.')[-1] # Неправильное расширение except: raise ErrorInvalid('file') try: load_image('app/static/tasks', x['image'], query['id'], file_type) # Ошибка загрузки изображения except: raise ErrorUpload('image') # Поля for par in ('text', 'tags'): if par in x: query[par] = x[par] db['tasks'].save(query) # Прикрепление задания к пользователю this.user['tasks'].append(query['id']) db['users'].save(this.user) # Обновление онлайн заданий if not process_edit: # ??? if '_id' in query: del query['_id'] query['image'] = get_preview('tasks', query['id']) this.socketio.emit('tasks_add', [query], namespace='/main') # Ответ res = { 'id': query['id'], } return res
def start(this, **x): # Проверка параметров check_params(x, (('id', True, int), )) # Не авторизован if this.user['admin'] < 3: raise ErrorAccess('token') # db_filter = { '_id': False, 'user': True, } task = db['tasks'].find_one({'id': x['id']}, db_filter) # Неправильное задание if not task: raise ErrorWrong('task') # space_id = next_id('space') space = { 'id': space_id, 'teacher': this.user['token'], 'student': task['user'], 'task': x['id'], # 'price': price, 'time': this.timestamp, 'status': 0, 'messages': [], } # db['space'].insert_one(space) # Запрос ученику this.socketio.emit('student_accept', { 'id': space_id, 'user': task['user'], }, namespace='/main') # Удалить онлайн задания user = db['users'].find_one({'token': task['user']}, { '_id': False, 'tasks': True }) db_condition = { 'id': { '$in': this.user['tasks'] + user['tasks'] }, } db_filter = { '_id': False, 'id': True, } tasks = [i for i in db['tasks'].find(db_condition, db_filter) if i] this.socketio.emit('tasks_del', tasks, namespace='/main') # Ответ res = { 'id': space_id, } return res
def heatmap(x): # global thread # with thread_lock: # if thread is None: # thread = sio.start_background_task(target=background_thread) sid = request.sid timestamp = time.time() # Отслеживание req = { 'time': timestamp, 'user': x['token'], 'method': 'heatmap', 'params': { 'tags': x['tags'] }, } db['actions'].insert_one(req) # if type(x['tags']) == str: x['tags'] = [x['tags']] discussion_id = next_id('discussions') discussion = { 'id': discussion_id, 'tags': x['tags'], 'time': timestamp, 'user': x['token'], 'status': 0, } db['discussions'].insert_one(discussion) # Обработка print('HEAT', '1', x['tags']) search(discussion_id) print('HEAT', '2') discussion = db['discussions'].find_one({'id': discussion_id}) discussion['status'] = 1 db['discussions'].save(discussion) try: texts, sets, inds, corpus, freq = vectorize(discussion_id) except: discussion['status'] = 4 else: for i in range(len(inds)): message = db['messages'].find_one({'_id': inds[i]}) message['preprocessed'] = sets[i] db['messages'].save(message) print('HEAT', '3', '\nDataset: {}\nCorpus: {}\n'.format(len(sets), len(corpus))) discussion = db['discussions'].find_one({'id': discussion_id}) discussion['status'] = 2 db['discussions'].save(discussion) lda_model, corpus, data_ready, data_inds, topics, prob = lda( discussion_id) topics_list = list(map(lambda x: x[1], lda_model.print_topics())) discussion = db['discussions'].find_one({'id': discussion_id}) discussion['topics'] = topics_list db['discussions'].save(discussion) for i in range(len(data_inds)): message = db['messages'].find_one({'_id': data_inds[i]}) message['topic'] = { 'name': topics[i], 'probability': float(round(prob[i], 3)), } db['messages'].save(message) print('HEAT', '4', '\Topics: {}'.format(topics_list)) discussion = db['discussions'].find_one({'id': discussion_id}) discussion['status'] = 3 db['discussions'].save(discussion) db_condition = { 'discussion': discussion_id, 'topic': { '$exists': True }, } db_filter = { '_id': False, 'topic.name': True, 'time': True, } messages = list(db['messages'].find(db_condition, db_filter)) # Время time_min = min(messages, key=lambda x: x['time'])['time'] times = [] time_start = time.gmtime(time_min) time_stop = time.gmtime() year_cur = time_start.tm_year month_cur = time_start.tm_mon while month_cur != time_stop.tm_mon or year_cur != time_stop.tm_year: if month_cur == 12: month_cur = 1 year_cur += 1 else: month_cur += 1 times.append( int(datetime.datetime(year_cur, month_cur, 1).timestamp())) # if len(times) >= 2: # topics = [[0 for _ in range(len(times) - 1)] for i in range(len(discussion['topics']))] # mes_all = len(messages) mes_count = [0 for _ in range(len(times) - 1)] # for i in range(len(times) - 1): for message in messages: if times[i] <= message['time'] < times[i + 1]: topics[message['topic']['name']][i] += 1 mes_count[i] += 1 for i in range(len(topics)): for j in range(len(topics[i])): if topics[i][j]: topics[i][j] /= mes_count[j] # discussion['timeline'] = times[:-1] discussion['result'] = topics discussion['status'] = 5 else: discussion['status'] = 4 db['discussions'].save(discussion)