Created
March 12, 2017 18:59
-
-
Save sandyjmacdonald/9810b723949717d68cd54b0138fe6ec8 to your computer and use it in GitHub Desktop.
Turn your Pimoroni Unicorn pHAT or Mood Light Kit into a Twitter-connected mood light that tracks the mood of your most recent tweets.
This file contains 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
## This script will turn your Unicorn pHAT or Mood Light Kit into | |
## a Twitter-connected mood light that tracks the mood of your most | |
## recent tweets. | |
## You'll need to install the unicornhat, textblob, and tweepy Python | |
## libraries, and run "python -m textblob.download_corpora" to download | |
## the corpora for textblob the first time you run it. | |
## Change the start_hue and end_hue values to use a different portion of | |
## the colour wheel. Change num_tweets to track a larger number of recent | |
## tweets. | |
## Remember to add create an app. at https://dev.twitter.com/ and add the | |
## consumer and access keys and secrets below. | |
import tweepy | |
import time | |
import colorsys | |
import unicornhat as uh | |
from textblob import TextBlob | |
consumer_key = "" | |
consumer_secret = "" | |
access_key = "" | |
access_secret = "" | |
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) | |
auth.set_access_token(access_key, access_secret) | |
api = tweepy.API(auth) | |
start_hue = 220 | |
end_hue = 320 | |
range_hue = (end_hue - start_hue) | |
num_tweets = 3 | |
weightings = range(1, num_tweets) | |
uh.set_layout(uh.PHAT) | |
uh.brightness(0.5) | |
while True: | |
avg_polarities = [] | |
for status in tweepy.Cursor(api.user_timeline).items(num_tweets): | |
status = " ".join([word for word in status.text.split() if not ("@" in word or "http" in word)]) | |
blob = TextBlob(status) | |
sent_polarities = [sentence.sentiment.polarity for sentence in blob.sentences] | |
polarity = sum(sent_polarities) / len(sent_polarities) | |
avg_polarities.append(polarity) | |
weighted = [x / y for x, y in zip(avg_polarities, weightings)] | |
avg_polarity = sum(weighted) / len(weighted) | |
avg_polarity = ((avg_polarity + 1) / 2) | |
hue = (start_hue + (avg_polarity * range_hue)) / 360.0 | |
r, g, b = [int(c * 255) for c in colorsys.hsv_to_rgb(hue, 1.0, 1.0)] | |
uh.clear() | |
for x in range(8): | |
for y in range(4): | |
uh.set_pixel(x, y, r, g, b) | |
uh.show() | |
time.sleep(25) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment