Last active
May 21, 2019 22:04
-
-
Save isaacmg/e99df126560ac36a4d8d657ae65a1982 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Use torchMoji to predict emojis from a single text input | |
""" | |
from __future__ import print_function, division, unicode_literals | |
import examples.example_helper | |
import json | |
import csv | |
import argparse | |
import numpy as np | |
import emoji | |
from flask import abort, Flask, jsonify, request | |
from torchmoji.sentence_tokenizer import SentenceTokenizer | |
from torchmoji.model_def import torchmoji_emojis | |
from torchmoji.global_variables import PRETRAINED_PATH, VOCAB_PATH | |
import logging | |
logging.basicConfig(level=logging.DEBUG) | |
app = Flask(__name__) | |
# Emoji map in emoji_overview.png | |
EMOJIS = ":joy: :unamused: :weary: :sob: :heart_eyes: \ | |
:pensive: :ok_hand: :blush: :heart: :smirk: \ | |
:grin: :notes: :flushed: :100: :sleeping: \ | |
:relieved: :relaxed: :raised_hands: :two_hearts: :expressionless: \ | |
:sweat_smile: :pray: :confused: :kissing_heart: :heartbeat: \ | |
:neutral_face: :information_desk_person: :disappointed: :see_no_evil: :tired_face: \ | |
:v: :sunglasses: :rage: :thumbsup: :cry: \ | |
:sleepy: :yum: :triumph: :hand: :mask: \ | |
:clap: :eyes: :gun: :persevere: :smiling_imp: \ | |
:sweat: :broken_heart: :yellow_heart: :musical_note: :speak_no_evil: \ | |
:wink: :skull: :confounded: :smile: :stuck_out_tongue_winking_eye: \ | |
:angry: :no_good: :muscle: :facepunch: :purple_heart: \ | |
:sparkling_heart: :blue_heart: :grimacing: :sparkles:".split(' ') | |
model = torchmoji_emojis(PRETRAINED_PATH) | |
def top_elements(array, k): | |
ind = np.argpartition(array, -k)[-k:] | |
return ind[np.argsort(array[ind])][::-1] | |
@app.route('/') | |
def hello(): | |
return "Hello, World" | |
@app.route('/api/v1/emojiSentiment', methods=['POST']) | |
def emoji_from_text(): | |
max_length = 30 | |
if not request.data: | |
abort(400) | |
message = json.loads(request.get_data(as_text=True)) | |
# Tokenizing using dictionary | |
with open(VOCAB_PATH, 'r') as f: | |
vocabulary = json.load(f) | |
text = message["message"] | |
st = SentenceTokenizer(vocabulary, max_length) | |
# Loading model | |
# Running predictions | |
tokenized, _, _ = st.tokenize_sentences([text]) | |
# Get sentence probability | |
prob = model(tokenized)[0] | |
# Top emoji id | |
emoji_ids = top_elements(prob, 5) | |
# map to emojis | |
emojis = map(lambda x: EMOJIS[x], emoji_ids) | |
return jsonify(list(emojis)), 200 | |
if __name__ == "__main__": | |
print("newest version") | |
app.run(host='0.0.0.0', debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment