def new_message(): with open('comments.json', 'r') as file: comments = json.loads(file.read()) if request.method == 'POST': newComment = request.form.to_dict() newComment['author'] = newComment['author'][:16] newComment['text'] = newComment['text'][:200] newComment['id'] = str(int(time.time() * 1000)) comments.append(newComment) with open('comments.json', 'w') as file: file.write(json.dumps(comments, indent=4, separators=(',', ': '))) pusher.trigger( 'messages', 'new_message', { "author": newComment['author'], "text": newComment['text'], "id": newComment['id'] }) return Response(json.dumps(comments), mimetype='application/json', headers={ 'Cache-Control': 'no-cache', 'Access-Control-Allow-Origin': '*' })
def send_message(): request_data = request.get_json() from_user = request_data.get('from_user', '') to_user = request_data.get('to_user', '') message = request_data.get('message', '') channel = request_data.get('channel') new_message = Message(message=message, channel_id=channel) new_message.from_user = from_user new_message.to_user = to_user db_session.add(new_message) db_session.commit() message = { "from_user": from_user, "to_user": to_user, "message": message, "channel": channel, "sentiment": getSentiment(message) } # Trigger an event to the other user pusher.trigger(channel, 'new_message', message) return jsonify(message)
def getSession(): """ Get user session details """ global sessionID time = datetime.now().replace(microsecond=0) if 'user' not in session: lines = (str(time) + userIP).encode('utf-8') session['user'] = hashlib.md5(lines).hexdigest() sessionID = session['user'] pusher.trigger( u'session', u'new', { u'ip': userIP, u'continent': userContinent, u'country': userCountry, u'city': userCity, u'os': userOS, u'browser': userBrowser, u'session': sessionID, u'time': str(time), }) data = [ userIP, userContinent, userCountry, userCity, userOS, userBrowser, sessionID, time ] create_session(c, data) else: sessionID = session['user']
def guest_user(): data = request.json pusher.trigger(u'general-channel', u'new-guest-details', { 'name': data['name'], 'email': data['email'] }) return json.dumps(data)
def updateTodo(item_id): data = { 'id': item_id, 'completed': json.loads(request.data).get('completed', 0) } pusher.trigger('todo', 'item-updated', data) return jsonify(data)
def parseVisitor(data): update_or_create_page(c, data) pusher.trigger(u'pageview', u'new', { u'page': data[0], u'session': sessionID, u'ip': userIP }) pusher.trigger(u'numbers', u'update', { u'page': data[0], u'session': sessionID, u'ip': userIP })
def request_chat(): request_data = request.get_json() from_user = request_data.get('from_user', '') to_user = request_data.get('to_user', '') to_user_channel = "private-notification_user_%s" % (to_user) from_user_channel = "private-notification_user_%s" % (from_user) try: bot = User.query.filter(User.id == to_user).one() except NoResultFound: print('Error! No bot (yet).') except MultipleResultsFound: print('Error! Wait what?') try: yolo.get_model(bot.username) except: print('Error! Cannot load model!') # check if there is a channel that already exists between this two user channel = Channel.query.filter( Channel.from_user.in_([from_user, to_user]) ) \ .filter( Channel.to_user.in_([from_user, to_user]) ) \ .first() if not channel: # Generate a channel... chat_channel = "private-chat_%s_%s" % (from_user, to_user) new_channel = Channel() new_channel.from_user = from_user new_channel.to_user = to_user new_channel.name = chat_channel db_session.add(new_channel) db_session.commit() else: # Use the channel name stored on the database chat_channel = channel.name data = { "from_user": from_user, "to_user": to_user, "from_user_notification_channel": from_user_channel, "to_user_notification_channel": to_user_channel, "channel_name": chat_channel, } # Trigger an event to the other user pusher.trigger(to_user_channel, 'new_chat', data) return jsonify(data)
def add_comment(): # Extract the request data request_data = request.get_json() id = request_data.get('id', '') username = request_data.get('username', '') comment = request_data.get('comment', '') socket_id = request_data.get('socket_id', '') if detect(comment) == 'en': print('English') test_data = ProcessData(df=list(comment), lang='en', max_seq_len=138) out = net.predict(model_path='../model/en_weights.best.hdf5', x=test_data.X) # Get the sentiment of a comment # text = TextBlob(comment) print(type(out[0][0]), out[0][0]) sentiment = int(out[0][0]) df = pd.DataFrame([{ "text": comment, "class": sentiment, "pedictions": str(out) }]) df.to_csv('new_train.csv', header=False, mode='a', index=False) else: print('Hindi') test_data = ProcessData(df=list(comment), lang='hi', max_seq_len=104) out = net.predict(model_path='../model/hi_weights.best.hdf5', x=test_data.X) # Get the sentiment of a comment # text = TextBlob(comment) print(type(out[0][0]), out[0][0]) sentiment = int(out[0][0]) df = pd.DataFrame([{ "text": comment, "class": sentiment, "pedictions": str(out) }]) df.to_csv('new_train.csv', header=False, mode='a', index=False) comment_data = { "id": id, "username": username, "comment": comment, "sentiment": sentiment, } print(comment_data) # Trigger an event to Pusher pusher.trigger("live-comments", 'new-comment', comment_data, socket_id) return jsonify(comment_data)
def delivered(request, id): message = models.Conversation.objects.get(pk=id) # verify it is not the same user who sent the message that wants to trigger a delivered event if request.user.id != message.user.id: socket_id = request.POST.get('socket_id', '') message.status = 'Delivered' message.save() message = { 'name': message.user.username, 'status': message.status, 'message': message.message, 'id': message.id } pusher.trigger(u'a_channel', u'delivered_message', message, socket_id) return HttpResponse('ok') else: return HttpResponse('Awaiting Delivery')
def broadcast(request): # collect the message from the post parameters, and save to the database message = models.Conversation(message=request.POST.get('message', ''), status='', user=request.user) message.save() # create an dictionary from the message instance so we can send only required details to pusher message = { 'name': message.user.username, 'status': message.status, 'message': message.message, 'id': message.id } #trigger the message, channel and event to pusher pusher.trigger(u'a_channel', u'an_event', message) # return a json response of the broadcasted message return JsonResponse(message, safe=False)
def send_message(): request_data = request.get_json() from_user = request_data.get('from_user', '') to_user = request_data.get('to_user', '') message = request_data.get('message', '') channel = request_data.get('channel') message = create_message(message=message, type='Text', to_user=to_user, from_user=from_user, channel=channel) # Trigger an event to the other user pusher.trigger(channel, 'new_message', message) return jsonify(message)
def new_message(): with open('comments.json', 'r') as file: comments = json.loads(file.read()) if request.method == 'POST': newComment = request.form.to_dict() newComment['author']=newComment['author'][:16] newComment['text']=newComment['text'][:200] newComment['id'] = str(int(time.time() * 1000)) comments.append(newComment) with open('comments.json', 'w') as file: file.write(json.dumps(comments, indent=4, separators=(',', ': '))) pusher.trigger('messages', 'new_message', { "author":newComment['author'], "text":newComment['text'], "id":newComment['id'] }) return Response(json.dumps(comments), mimetype='application/json', headers={'Cache-Control': 'no-cache', 'Access-Control-Allow-Origin': '*'})
def add_comment(): # Extract the request data request_data = request.get_json() id = request_data.get('id', '') username = request_data.get('username', '') comment = request_data.get('comment', '') socket_id = request_data.get('socket_id', '') # Get the sentiment of a comment text = TextBlob(comment) sentiment = text.polarity comment_data = { "id": id, "username": username, "comment": comment, "sentiment": sentiment, } # Trigger an event to Pusher pusher.trigger("live-comments", 'new-comment', comment_data, socket_id) return jsonify(comment_data)
def request_chat(): request_data = request.get_json() from_user = request_data.get('from_user', '') to_user = request_data.get('to_user', '') to_user_channel = "private-notification_user_%s" % (to_user) from_user_channel = "private-notification_user_%s" % (from_user) # check if there is a channel that already exists between this two user channel = Channel.query.filter(Channel.from_user.in_([from_user, to_user])) \ .filter(Channel.to_user.in_([from_user, to_user])) \ .first() if not channel: # Generate a channel... chat_channel = "private-chat_%s_%s" % (from_user, to_user) new_channel = Channel() new_channel.from_user = from_user new_channel.to_user = to_user new_channel.name = chat_channel db_session.add(new_channel) db_session.commit() else: # Use the channel name stored on the database chat_channel = channel.name data = { "from_user": from_user, "to_user": to_user, "from_user_notification_channel": from_user_channel, "to_user_notification_channel": to_user_channel, "channel_name": chat_channel, } # Trigger an event to the other user pusher.trigger(to_user_channel, 'new_chat', data) return jsonify(data)
def request_chat(): request_data = request.get_json() from_user = request_data.get('from_user', '') to_user = request_data.get('to_user', '') to_user_channel = "private-notification_user_%s" % (to_user) from_user_channel = "private-notification_user_%s" % (from_user) # check if a channel exists between the two users channel = Channel.query.filter(Channel.from_user.in_([from_user, to_user])) \ .filter(Channel.to_user.in_([from_user, to_user])) \ .first() if not channel: # generate new channel chat_channel = "private-chat_%s_%s" % (from_user, to_user) new_channel = Channel() new_channel.from_user = from_user new_channel.to_user = to_user new_channel.name = chat_channel db_session.add(new_channel) db_session.commit() else: # Use existing channel chat_channel = channel.name data = { "from_user": from_user, "to_user": to_user, "from_user_notification_channel": from_user_channel, "to_user_notification_channel": to_user_channel, "channel_name": chat_channel, } # an event is triggered to the other use pusher.trigger(to_user_channel, 'new_chat', data) return jsonify(data)
def removeTodo(item_id): data = {'id': item_id} pusher.trigger('todo', 'item-removed', data) return jsonify(data)
def addTodo(): # loads json data from request data = json.loads(request.data) # trigger item-added event on to-do channel pusher.trigger('todo', 'item-added', data) return jsonify(data)
def say(request): # IMPLEMENT data = json.loads(request.body) print('mudroom-' + data['room']) pusher.trigger('mudroom-' + data['room'], 'message', data) return JsonResponse(data, safe=True, status=201)
def send_file(): request_data = request.form from_user = request_data.get('from_user', '') to_user = request_data.get('to_user', '') channel = request_data.get('channel') file = request.files['file'] bot_id = to_user name = channel + datetime.datetime.now().strftime("%Y%m%d%H%M%S") inp_dir = './data/input/{}.jpg'.format(name) file.save(inp_dir) inp_token = upload_file('input', inp_dir) inp_url = 'https://firebasestorage.googleapis.com/v0/b/narupedia-d9cf9.appspot.com/o/input%2F' + name + '.jpg?alt=media&token=' + inp_token inp_img = create_message(message=inp_url, type='Image', to_user=to_user, from_user=from_user, channel=channel) pusher.trigger(channel, 'new_message', inp_img) message = create_message(message="I'm onto it, please wait for a bit.", type='Text', to_user=from_user, from_user=to_user, channel=channel) pusher.trigger(channel, 'new_message', message) try: bot = User.query.filter(User.id == bot_id).one() except NoResultFound: print('Error! No bot (yet).') except MultipleResultsFound: print('Error! Wait what?') try: model = yolo.get_model(bot.username) except: print('Error! Cannot get model!') out_dir = './data/output/{}'.format(name) r = yolo.detect(model, inp_dir, out_dir=out_dir) r = [x for x in r if x['prob'] > 0.5] messages = [] messages.append('I have detected %d object(s) in the images.' % len(r)) for idx, det in enumerate(r): prob = det['prob'] if prob > 0.8: messages.append('[%d] I detected a [%s].' % (idx, det['class'])) elif prob > 0.5: messages.append('[%d] I am not so sure but it may be a [%s]' % (idx, det['class'])) # elif prob > 0.3: # messages.append('[%d] I really do not know what this is. My best guess is that it is a [%s].' % (idx, det['class'])) out_token = upload_file('output', out_dir + '.jpg') out_url = 'https://firebasestorage.googleapis.com/v0/b/narupedia-d9cf9.appspot.com/o/output%2F' + name + '.jpg?alt=media&token=' + out_token # inp_url, out_url, messages = process_query(bot_id, file, name) out_img = create_message(message=out_url, type='Image', to_user=from_user, from_user=to_user, channel=channel) pusher.trigger(channel, 'new_message', out_img) for m in messages: message = create_message(message=m, type='Text', to_user=from_user, from_user=to_user, channel=channel) pusher.trigger(channel, 'new_message', message) return jsonify(messages)