-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
235 lines (193 loc) · 7.31 KB
/
app.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
# Music Genre Machine
# Python Flask app that chooses words from predefined lists
# -----
import random, os, logging, httpimport
# imports for firestore
import firebase_admin
from firebase_admin import credentials
from google.cloud import firestore
from firebase_admin import firestore
from flask import Flask, render_template, request, flash, redirect, url_for
from difflib import SequenceMatcher
from UrlShare import UrlShare
with httpimport.github_repo(
"MothmanCapital", "pyunsplash", branch="add-support-for-embed-urls"
):
from pyunsplash import PyUnsplash
# initialize firestore connection
cred = credentials.Certificate("genremachine.json")
firebase_admin.initialize_app(cred)
client_id = os.environ["UNSPLASH_ID"]
client_secret = os.environ["UNSPLASH_KEY"]
redirect_uri = os.environ["UNSPLASH_REDIR"]
# Initialize PyUnsplash app logging
logger = logging.getLogger()
logging.basicConfig(filename="app.log", level=logging.DEBUG)
logging.getLogger(PyUnsplash.logger_name).setLevel(logging.DEBUG)
wordsCombined = []
exclusiveTags = []
phraseLength = 3
def readFiles(filename, listToReadInto):
fileHolder = open(filename, "r")
for line in fileHolder:
if line.strip() and (line != None) and (line[0] != "#"):
listToReadInto.append(line.strip())
return listToReadInto
fileHolder.close()
# Could be moved into the main app route to refresh word list live instead of having to restart the app
readFiles("combined.txt", wordsCombined)
readFiles("exclusive-tags.txt", exclusiveTags)
def processWordList(listToProcess):
wordStorage = []
for w in listToProcess:
wordTemp = []
w = w.strip()
wordTemp.append(w.split(";")[0])
wordTemp.append(w.split(";")[1].split(","))
wordStorage.append(wordTemp)
return wordStorage
def getWordByTags(wordListFilter, *tagFilterList):
randomWord = ""
matchingWordList = []
exclusiveTagsFilterList = []
inclusiveTagsFilterList = []
for t in tagFilterList:
t = str(t)
if t != "None":
if t in exclusiveTags:
exclusiveTagsFilterList.append(t)
# print("exclusive tag: " + t)
else:
inclusiveTagsFilterList.append(t)
# print("regular tag: " + t)
else:
getWordByTags(wordListFilter, tagFilterList)
for l in wordListFilter:
if all(search in l[1] for search in inclusiveTagsFilterList):
# matchingWordList.append(l[0])
if all(search not in l[1] for search in exclusiveTagsFilterList):
matchingWordList.append(l[0])
if len(matchingWordList) > 0:
randomWord = random.choice(matchingWordList)
return randomWord
def getTags(wordToCheck, wordsList):
wordIdx = [i for i, ele in wordsList].index(wordToCheck)
# print("wordIdx: ")
# print(wordIdx)
return wordsList[wordIdx][1]
def getWordWithoutTags(wordListFilter, *tagFilterList):
returnList = []
for l in wordListFilter:
if all(search in l[1] for search in tagFilterList):
returnList.append(l[0])
randomWord = random.choice(returnList)
return randomWord
def randColor():
color = "%06x" % random.randint(0, 0xFFFFFF)
return str(color)
def getUnsplashPhoto(search_term, w=640, h=480):
# instantiate pyunsplash connection object
api = PyUnsplash(api_key=client_id)
print(search_term.strip("-"))
try:
# Retrieve random photo matching search term from unsplash
unsplash_photo_coll = api.photos(
type_="random", count=1, query=search_term.strip("-")
)
# retrieve raw url of photo
unsplash_photo = (
next(unsplash_photo_coll.entries).body["urls"]["raw"]
+ "&w="
+ str(w)
+ "&h="
+ str(h)
)
bg_image = r'url("' + unsplash_photo + r'")'
except:
bg_image = (
"linear-gradient("
+ str(random.randint(0, 180))
+ "deg, #"
+ randColor()
+ ", #"
+ randColor()
+ ")"
)
return bg_image
app = Flask(__name__)
@app.route("/", defaults={"share_uuid": None})
@app.route("/<share_uuid>")
def index(share_uuid):
if share_uuid == None:
print("-----new genre-----")
wordsList = processWordList(wordsCombined)
phrase = []
phraseTags = []
unsplash_search_eligible = []
phrase_result = ""
for phraseIdx in range(phraseLength):
pickedWord = getWordByTags(wordsList, phraseIdx)
pickedWordTags = getTags(pickedWord, wordsList)
# check to see if word can be photo searched
if "p" in pickedWordTags:
unsplash_search_eligible.append(pickedWord)
for pt in pickedWordTags:
if not pt.isdecimal():
# not appending tags indicating position
# which are numeric
phraseTags.append(pt)
if phraseIdx == 0:
# If index is zero we are getting adjective 1 and not using sequence matcher
phrase.append(pickedWord)
else:
# if we aren't on the first word in the phrase...
# compare current word with previous word in phrase
s = SequenceMatcher(None, phrase[phraseIdx - 1], pickedWord)
while s.ratio() > 0.8:
print("Word too similar:")
print(pickedWord)
pickedWord = getWordByTags(wordsList, str(phraseIdx), phraseTags)
s = SequenceMatcher(None, phrase[phraseIdx - 1], pickedWord)
phrase.append(pickedWord)
# Pick background photo
print("searchable words: ")
print(unsplash_search_eligible)
if len(unsplash_search_eligible) > 0:
search_term = random.choice(unsplash_search_eligible)
print("searching for " + search_term)
bg_image = getUnsplashPhoto(search_term)
else:
print(
"default search for ocean picture, none of the random terms look like they would work"
)
search_term = "ocean"
bg_image = getUnsplashPhoto("ocean")
print(bg_image)
# Join dashed words together
for phraseIdx in range(phraseLength):
if not (phrase[phraseIdx].endswith("-")):
phrase_result += phrase[phraseIdx] + " "
else:
phrase_result += phrase[phraseIdx]
print(phrase_result)
new_shared_url = UrlShare(phrase_result, bg_image, search_term)
share_redir = "/" + new_shared_url.uuid
new_shared_url.commit()
return redirect(share_redir)
else:
shared_url = UrlShare(uuid=share_uuid)
print(shared_url)
db = firestore.Client(project="genremachine-2e8a4")
collection = db.collection("shared_urls")
doc = collection.document(share_uuid).get().to_dict()
return render_template(
"index.html",
phrase_result=doc['phrase'],
bg_image=doc['img'],
link_preview_img=str(doc['img'])[5:-2],
search_term=doc['search'],
clicks=doc['clicks']
)
if __name__ == "__main__":
app.run()
gunicorn_logger = logging.getLogger("gunicorn.error")