In [1]:
import json
import urllib.request
import random
import PIL
import word2vec
import sys
import memegenerator
import twitter_credentials
import scipy.ndimage
In [2]:
model = word2vec.load('../text8.bin')
In [3]:
consumer_key = twitter_credentials.consumer_key
consumer_secret = twitter_credentials.consumer_secret
access_token = twitter_credentials.access_token
access_token_secret = twitter_credentials.access_token_secret
In [4]:
import tweepy
# == OAuth Authentication ==
#
# This mode of authentication is the new preferred way
# of authenticating with Twitter.
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)
# If the application settings are set for "Read and Write" then
# this line should tweet out the message to your account's
# timeline. The "Read and Write" setting is on https://dev.twitter.com/apps
# api.update_status(status='Updating using OAuth authentication via Tweepy!')
In [5]:
public_tweets = api.home_timeline()
In [6]:
valid_tweets = []
best_tweets = []
for t in public_tweets:
words = t.text.split()
words = [w for w in words if w in model.vocab]
words2 = [w for w in words if len(w) > 3]
if len(words) < 3:
continue
if len(words2) >= 3:
best_tweets.append(t)
valid_tweets.append(t)
tweet = random.choice(public_tweets)
if best_tweets:
tweet = random.choice(best_tweets)
In [7]:
words = tweet.text.split()
words2 = [w for w in words if len(w) > 3]
words2 = [w for w in words2 if w in model.vocab]
ws = []
while(len(ws) <= 2):
using = words
if words2:
using = words2
w = random.choice(using)
using.pop(using.index(w))
if w in model.vocab:
ws.append(w)
In [8]:
indexes, metrics = model.analogy(pos=[ws[0], ws[1]], neg=[ws[2]], n=10)
In [9]:
ws.append(model.vocab[indexes][0])
In [10]:
if using:
ws.append(using[0])
else:
ws.append(ws[0])
In [11]:
print(tweet.text)
print(ws)
In [12]:
url_template = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%s&imgsz=xlarge&imgtype=photo&as_sitesearch=flickr.com'
url = url_template % ws[4]
result = urllib.request.urlopen(url)
js = json.loads(result.read().decode())
image_url = js['responseData']['results'][0]['unescapedUrl']
filename = urllib.request.urlretrieve(image_url)[0]
topString = '%s is to %s' % (ws[0], ws[1])
bottomString = "as %s is to %s" % (ws[2], ws[3])
memegenerator.make_meme(topString, bottomString, filename)
In [13]:
imagename = 'temp.png'
%matplotlib inline
In [14]:
from PIL import Image
im = Image.open(imagename)
im.show()
In [ ]:
In [ ]: