-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
107 lines (83 loc) · 3.66 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import json, os, glob, random, time, requests
import tweepy
import urllib.request
credentials = json.loads(open('credentials.json').read())
TwitterAuth = tweepy.OAuthHandler(credentials['twitterConsumerKey'], credentials['twitterConsumerSecret'])
TwitterAuth.set_access_token(credentials['twitterAccessToken'], credentials['twitterAccessSecret'])
TwitterApi = tweepy.API(TwitterAuth)
def getQueryTerm():
return "&query=" + random.choice(['mountains', 'nature', 'forest', 'jungle', 'beach', 'autumn', 'winter', 'summer', 'spring', 'waterfall', 'rain'])
def getImage():
random_url = 'https://api.unsplash.com/photos/random?featured=true'
headers = {'Authorization': 'Client-ID ' + credentials['unsplashAccessId']}
img = requests.get(random_url, headers=headers).json()
creditName = img['user'].get('name', img['user'].get('username'))
if img['user'].get('twitter_username'):
creditName = '@' + img['user']['twitter_username']
return {
'url': img['urls']['regular'] + '.jpg',
'credit': creditName,
'creditLink': img['links']['self'].replace('api.', '')
}
def downloadImage(imgURL):
try:
savePath = '/app/images/input/' + str(random.randint(1,1000)) + '.jpg'
urllib.request.urlretrieve(imgURL, savePath)
time.sleep(5)
return savePath
except Exception as e:
TwitterApi.send_direct_message(credentials['myTwitter'], text='download image failed: ' + str(e))
def getArtStyle():
availableStyles = glob.glob('ckpt_files/*')
return random.choice(availableStyles)
def styleImage(imgPath, stylePath):
try:
script = str('python evaluate.py --checkpoint ' + stylePath + ' --in-path ' + '/app/images/input/' + ' --out-path ' + '/app/images/output/' + ' --allow-different-dimensions')
os.system(script)
return imgPath.replace('input','output')
except Exception as e:
TwitterApi.send_direct_message(credentials['myTwitter'], text='styling image failed: ' + str(e))
def genDescription(data):
if data.get('credit'):
return '{} applied to a photo by {}. \nOriginal: {} \n #tensorflow #styletransfer'.format(data['style'], data['credit'], data['creditLink'])
else:
return '{} applied to an @unsplash featured photo. \nOriginal: {} \n #tensorflow #styletransfer'.format(data['style'], data['creditLink'])
def tweetArt(imgPath, post):
try:
time.sleep(3)
TwitterApi.update_with_media(
str(imgPath),
status=post
)
except Exception as e:
TwitterApi.send_direct_message(credentials['myTwitter'], text='Tweeting image failed: ' + str(e))
def removeImages():
outputs = glob.glob('/app/images/output/*')
for f in outputs:
os.remove(f)
inputs = glob.glob('/app/images/input/*')
for f in inputs:
os.remove(f)
def genNewPost():
image = getImage()
imgPath = downloadImage(image['url'])
artStylePath = getArtStyle()
artStyleName = artStylePath.split("/")[-1].replace(".ckpt","").replace("_"," ").title()
image['style'] = "'{}' art style".format(artStyleName)
styledImgPath = styleImage(imgPath, artStylePath)
description = genDescription(image)
tweetArt(styledImgPath, description)
removeImages()
def main():
sleepTime = 60 * 60 * 4
while True:
try:
genNewPost()
time.sleep(sleepTime)
except Exception as e:
TwitterApi.send_direct_message(credentials['myTwitter'], text='New post failed: ' + str(e))
time.sleep(5)
print(e)
TwitterApi.send_direct_message(credentials['myTwitter'], text='AI_Artify is shutting down')
if __name__ == '__main__':
main()