def mood_from_picture(cls, picture): headers = { 'Ocp-Apim-Subscription-Key': get_secret('microsoft_pic', 'key_1'), 'Content-Type': 'application/octet-stream' } pic_data = picture.read() r = requests.post(PICTURE_ANALYSIS_URL, headers=headers, data=pic_data) response_json = r.json() logger.debug(response_json) data = response_json[0]["scores"] # Aggregate emotion emotions = { "happy": data["happiness"], "sad": data["fear"] + data["sadness"], "angry": data["anger"] + data["disgust"] + data["contempt"], "neutral": data["neutral"], } logger.debug(response_json) # Find strongest emotion max_val = emotions["neutral"] max_emotion = 'neutral' for key, value in emotions.items(): if value > max_val: max_val = value max_emotion = key # Standardize the emotion return max_emotion
def _mood_from_text(cls, text): headers = { 'Ocp-Apim-Subscription-Key': get_secret('microsoft_text', 'key_1') } body = {"documents": [{"language": "en", "id": "0", "text": text}]} r = requests.post(TEXT_ANALYSIS_URL, headers=headers, data=json.dumps(body)) response_json = r.json() return response_json['documents'][0]["score"]
def mood_from_twitter(cls, handle): key = get_secret('twitter', 'consumer_key') secret = get_secret('twitter', 'consumer_secret') auth = tweepy.OAuthHandler(key, secret) api = tweepy.API(auth) most_recent_tweet = api.user_timeline(screen_name=handle, count=1)[0] tweet_text = most_recent_tweet.text # Strip out @'s and hashtags for purity clean = re.sub(r'@\w+\s*', '', tweet_text) clean = re.sub(r'#', '', clean) mood = cls._mood_from_text(clean) if (mood > 0.7): return 'happy' elif (mood < 0.3): return 'sad' return 'neutral'
def get_stream_url(track_id): url = "https://api.soundcloud.com/i1/tracks/%s/streams" % track_id secret = get_secret("soundcloud", "client_id") params = { "client_id": secret, "app_version": 1479467323, } res = requests.get(url, params) return res.json()
def get_playlist_tracks(playlist_id): url = "https://api-v2.soundcloud.com/playlists/%s" % playlist_id secret = get_secret("soundcloud", "client_id") params = { "representation": "full", "client_id": secret, "app_version": 1479467323, } res = requests.get(url, params) data = res.json() tracks = data["tracks"] full_tracks = [t for t in tracks if "user" in t] partial_tracks = [t for t in tracks if "user" not in t] if len(partial_tracks) > 0: partial_ids = [str(t["id"]) for t in partial_tracks] url = "https://api-v2.soundcloud.com/tracks" params = { "ids": ",".join(partial_ids), "client_id": secret, "app_version": 1479467323, } res = requests.get(url, params) data = res.json() full_tracks.extend(data) random.shuffle(full_tracks) return full_tracks
def index_view(request): client_id = get_secret("soundcloud", "client_id") return {"client_id": client_id}