-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcocktaildb.py
406 lines (322 loc) · 11.9 KB
/
cocktaildb.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
import requests
import json
from string import digits, ascii_lowercase as INITIALS
from itertools import chain
from shutil import copyfileobj
from PIL import Image
import sys
import os
#Internet connection check
try:
internet = requests.get("https://www.httpbin.org/status/200")
except:
print("YOU DON'T HAVE INTERNET ACCESS, CLOSING PROGRAM!")
sys.exit()
#OS CHECK
os_ = sys.platform
if os_ == "win32":
pass
else:
print("#@#LINUX DETECTED, CORRECT FUNCTIONING OF THIS PROGRAM IS NOT GUARANTEED (TESTED FOR WINDOWS ONLY)#@#")
#COLOR FOR COMMAND PROMPT
class Colors:
def r():
os.system("color 4")
def b():
os.system("color 3")
def y():
os.system("color E")
c = Colors
def logo():
LOGO = """
_____ _ _ _ _ _____ ____
/ ____| | | | | (_) | | | __ \ | _ \
| | ___ ___ | | __ | |_ __ _ _ | | | | | | | |_) |
| | / _ \ / __| | |/ / | __| / _` | | | | | | | | | | _ <
| |____ | (_) | | (__ | < | |_ | (_| | | | | | | |__| | | |_) |
\_____| \___/ \___| |_|\_\ \__| \__,_| |_| |_| |_____/ |____/
"""
print(LOGO)
HELP = """[INTRO]
-h OR --help: Show this menu.
[COCKTAIL DATABASE]
-s: Search cocktail by name.
-r: Returns information for a random cocktail!
-i: Search information for a cocktail ingredient!
--byi: Returns a list of cocktails that contain a specified ingredient.
--bys INITIAL: Returns a list of cocktails starting by a letter (example: --searchby a)
--img: Download an image of a cocktail and open it.
"""
LOGO = r"""
() () () /
() () () /
______________/___
\ / / Pythonic
\^^^^^^^^^^/^^^/
\ ___/ /
\ ( ) /
\ (___) / Cocktails...
\ / /
\ /
\ /
\/
||
||
||
||
||
/\
/;;\
==============
"""
#Functions for each api request and information choice
def search_cocktail(name:str, random:bool = False) -> str:
if not random:
URL = f"https://www.thecocktaildb.com/api/json/v1/1/search.php?s={name}"
else:
URL = "https://www.thecocktaildb.com/api/json/v1/1/random.php"
try:
req = requests.get(URL)
content = json.loads(req.text)
#Access stuff
content = content["drinks"]
if not content:
os.system("color E")
return print(f"\nNothing found for {name}!\n")
except Exception as ex:
os.system("color 4")
return print(f"\nUh Oh, something was done wrong!\nDetails: {ex}")
#print(content)
#Access every dictionary in list and gather values
for c,element in enumerate(content,start=1):
print(f"\n\n===COCKTAIL VARIATION {c}===\n" if len(content) > 1 else "")
#strIngredients and strMeasures
ing = [f"strIngredient{x}" for x in range(1, 21)]
msr = [f"strMeasure{x}" for x in range(1, 21)]
ingredients = []
measures = []
#Get all possible existing ingredients in a range from 1 to 20
for n in ing:
try:
current_ingredient = element[n]
ingredients.append(current_ingredient)
except:
continue
for n in msr:
try:
current_measure = element[n]
measures.append(current_measure)
except:
continue
#Remove NoneType values
ingredients = list(filter(lambda x: x is not None, ingredients))
measures = list(filter(lambda x: x is not None, measures))
#Assign number on each elemnt
for i in range(len(measures)):
measures[i] = f"[{str(i+1)}] {measures[i]}" #Assign the number i that takes the value of each list's index and format it to the ingredients name (weird to explain)
m_i = list(zip(measures,ingredients))
#Get info
name = element["strDrink"]
category = element["strCategory"]
glass:str = element["strGlass"]
alcohol: str = ["Yes" if element["strAlcoholic"] == "Alcoholic" else "No"]
instructions: str = element["strInstructions"]
#PRINTING
print(f"#Cocktail name: {name.title()}")
print(f"#Category: {category}")
print(f"#Glass: {glass}")
print(f"#Alcoholic: {alcohol[0]}")
print("\n###INGREDIENTS###")
for x in m_i:
print(f"{x[0]}-> {x[1]}")
print(f"\n###INSTRUCTIONS###\n{instructions}")
#Search by initial
def search_by_initial(initial:str) -> str:
URL = f"https://www.thecocktaildb.com/api/json/v1/1/search.php?f={initial}"
try:
req = requests.get(URL)
content = json.loads(req.text)
#Access stuff
content = content["drinks"]
if not content:
os.system("color E")
return print(f"\nNothing found for {initial}!\n")
except Exception as ex:
c.r()
return print(f"\nUh Oh, something was done wrong!\nDetails: {ex}")
#Get list of values for key -> "strDrink" from json
drinks = [dic["strDrink"] for dic in content]
print(f"Found {len(drinks)} cocktails!\n")
for count, cocktail in enumerate(drinks,start=1):
print(f"[{count}] {cocktail}")
def search_ingredient(name:str) -> str:
URL = f"https://www.thecocktaildb.com/api/json/v1/1/search.php?i={name}"
try:
req = requests.get(URL)
content = json.loads(req.text)
#Access stuff
content = content["ingredients"]
if not content:
os.system("color E")
return print(f"\nNothing found for {name}!\n")
except Exception as ex:
c.r()
return print(f"\nUh Oh, something was done wrong!\nDetails: {ex}")
cn = content[0]
name: str = cn["strIngredient"]
desc: str = cn["strDescription"]
type_: str = cn["strType"]
has_alcohol: str = "Yes" if cn["strAlcohol"] == "Yes" else "No"
print(f"NAME: {name}\n")
print(f"###DESCRIPTION###\n")
print(desc)
print(f"\nType: {type_}")
print(f"Alcoholic: {has_alcohol}")
def search_by_ingredient(ingredient:str) -> str:
URL = f"https://www.thecocktaildb.com/api/json/v1/1/filter.php?i={ingredient}"
try:
req = requests.get(URL)
content = json.loads(req.text)
#Access stuff
content = content["drinks"]
if not content:
os.system("color E")
return print(f"\nNothing found for {ingredient}!\n")
except Exception as ex:
c.r()
return print(f"\nUh Oh, something was done wrong!\nDetails: {ex}")
#Get values of each dictionary in list
values = [cnt["strDrink"] for cnt in content]
for count, v in enumerate(values, start=1):
print(f"[{count}] {v}")
def get_img(cocktail:str) -> str:
URL = f"https://www.thecocktaildb.com/api/json/v1/1/search.php?s={cocktail}"
try:
req = requests.get(URL)
content = json.loads(req.text)
#Access stuff
content = content["drinks"]
if not content:
os.system("color E")
return print(f"\nNothing found for {cocktail}!\n")
except Exception as ex:
c.r()
return print(f"\nUh Oh, something was done wrong!\nDetails: {ex}")
cocktail_name = content[0]["strDrink"]
thumbnail_url = content[0]["strDrinkThumb"]
file = cocktail_name + ".jpg"
#Save file
try:
image_req = requests.get(thumbnail_url, stream=True)
if image_req.status_code == 200:
with open(file, 'wb') as fl:
copyfileobj(image_req.raw,fl)
print(f"\nFile saved in {os.path.join(os.getcwd(), file)}")
img = Image.open(file).show()
else:
raise Exception(f"{thumbnail_url} returned status code: {image_req.status_code}")
except Exception as ex:
c.r()
print(f"\n{ex}\n")
return
def main():
if len(sys.argv) == 2:
#Commands here
cmd = sys.argv[1]
match cmd:
#COMMANDS MENU
case "-h":
print(HELP)
return
case "--help":
print(HELP)
return
#Search for cocktail by name
case "-s":
#Question and "left-blank" check
while True:
n = input("Enter a cocktail to search: ")
if not n:
c.y()
print("\nYou can't leave this field empty!\n")
continue
break
c.b()
search_cocktail(n)
return
case "-r":
search_cocktail("",True)
return
case "-i":
#Question and "left-blank" check... again
while True:
n = input("Enter an ingredient to search: ")
if not n:
c.y()
print("\nYou can't leave this field empty!\n")
continue
break
c.b()
search_ingredient(n)
return
case "--byi":
#Question and "left-blank" check... again
while True:
n = input("Enter ingredient: ")
if not n:
c.y()
print("\nYou can't leave this field empty!\n")
continue
break
c.b()
print(f"THE FOLLOWING COCKTAILS CAN BE MADE WITH {n.upper()}\n")
search_by_ingredient(n)
return
#Search for cocktail by name (get image url)
case "--img":
#Question and "left-blank" check
while True:
n = input("Enter a cocktail to search: ")
if not n:
c.y()
print("\nYou can't leave this field empty!\n")
continue
break
c.b()
get_img(n)
return
case _:
c.r()
print("This command does nothing!\n".upper())
return
#EXAMPLE: cocktaildb.py --command 3rd_argument
elif len(sys.argv) == 3:
cmd1 = sys.argv[1]
cmd2 = sys.argv[2]
#Get list of cocktails by initial ^_^
if cmd1 == "--bys" and cmd2:
cmd2 = cmd2.lower()
#Error handling
if not cmd2 in list(chain(INITIALS,digits)):
c.r()
print("\nPlease enter a valid letter! (Example: \"a\")\n")
return
search_by_initial(cmd2)
return
#No command given
else:
c.y()
print("Type --help or -h for a list of commands!\n")
return
if __name__ == "__main__":
#DEFAULT COLOR and clear screen
if os_ == "linux":
os.system("clear")
else:
os.system("cls")
c.b()
NAME = sys.argv[0].split("\\")[-1]
logo()
print(f"WELCOME TO {NAME.upper()}!\nAPI: https://www.thecocktaildb.com/api.php\n")
main()
print("\n" + LOGO)