Amazing-Python-Scripts

Форк
0
431 строка · 15.9 Кб
1
# 🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀 WELCOME TO SPACE NEWS AI CHAT MODEL 🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀
2

3
from IPython import display
4
from PIL import Image
5
from playsound import playsound
6
from gtts import gTTS
7
import matplotlib.pyplot as plt
8
import urllib.request
9
import random
10
import io
11
import os
12
import requests
13
import time
14
import nasapy
15
print('🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\n')
16

17
# Enter the API key of NASA
18
Api_Key = input("Enter the NASA API Key: ")
19

20
# Importing modules
21

22
# Function which handles the news data of space
23

24

25
def spaceNews():
26
    print("\nWhat day would you like to know ?")
27

28
    # Date must be between 16 Jun, 1995 and till now
29
    Date = input("Enter date {yyyy-mm-dd}: ")
30

31
    # Fetching data from the nasa
32
    print("\nExtracting Data......")
33
    print('\nPlease wait.....')
34
    Url = "https://api.nasa.gov/planetary/apod?api_key=" + str(Api_Key)
35
    Params = {'date': str(Date)}
36
    r = requests.get(Url, params=Params)
37

38
    # Parsing the fetched data for displaying
39
    Data = r.json()
40

41
    # Parsing the extracted data
42
    Info = Data['explanation']
43
    Title = Data['title']
44
    Image_Url = Data['url']
45

46
    # Requesting for the image url to fetch and store into an array
47
    Image_r = requests.get(Image_Url)
48
    FileName = str(Date) + '.jpg'
49
    # Saving the images
50
    with open(FileName, 'wb') as f:
51
        f.write(Image_r.content)
52
    img = Image.open(FileName)
53

54
    # Clear the terminal for the next operation
55
    os.system('cls' if os.name == 'nt' else 'clear')
56
    print('\n🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\n')
57

58
    # Displaying the fetched data
59
    img.show()
60
    print(f"\nTitle of this news - {Title}")
61
    print(f"\nBrief Description \n\n{Info}")
62
    print(f"\nFileName - {FileName}\n")
63

64
# Function which fetch the mars images of different dates
65

66

67
def MarsImage():
68
    date = input("\nEnter date {yyyy-mm-dd}: ")
69
    url = f"https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date={date}&api_key={Api_Key}"
70

71
    # Fetching data from the internet
72
    r = requests.get(url)
73
    Data = r.json()
74

75
    # Extracting data from the fetched data set
76
    Photos = Data['photos'][0:9]
77

78
    if Data['photos'] == []:
79
        print("\nSorry, No data found!\n")
80
    else:
81
        for index, photo in enumerate(Photos):
82
            # Creating a lists of different values
83
            camera = photo['camera']
84
            full_camera_name = camera['full_name']
85
            date_of_photo = photo['earth_date']
86
            img_url = photo['img_src']
87

88
            # Downloading images from the internet
89
            p = requests.get(img_url)
90
            img = f'{index}.jpg'
91
            with open(img, 'wb') as file:
92
                file.write(p.content)
93
            os.startfile(img)
94

95
            print(
96
                f'Image "{index}.jpg" was captured with {full_camera_name} on {date_of_photo}\n')
97
            time.sleep(1)
98

99
# Function whixh tells about the number of asteroids in a range of dates
100

101

102
def Astro():
103
    # Getting two dates from the user for calculation of number of asteroids in between this range
104
    print("\nDifference between start and last dates is not more than 7 days.")
105
    print("\nNow, What's the start date ?")
106
    start_date = input("Enter date {yyyy-mm-dd}: ")  # Start date
107
    print("\nAnd the last date ?")
108
    end_date = input("Enter date {yyyy-mm-dd}: ")  # Last date
109

110
    url = f"https://api.nasa.gov/neo/rest/v1/feed?start_date={start_date}&end_date={end_date}&api_key={Api_Key}"
111

112
    # Fetching data from the internet
113
    r = requests.get(url)
114
    Data = r.json()
115

116
    # Clear the terminal for the next operation
117
    os.system('cls' if os.name == 'nt' else 'clear')
118
    print('\n🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\n')
119

120
    # Extracting data from the fetched data set
121
    Total_Astro = Data['element_count']
122
    print(
123
        f"\nTotal no. of asteroid falling on The Earth between {start_date} and {end_date} is : {Total_Astro} Asteroids\n")
124

125
    # enumarating the objects one by one
126
    neo = Data['near_earth_objects']
127

128
    for body in neo[start_date]:
129
        # parsing the object to extract 3 different values
130
        id = body['id']
131
        name = body['name']
132
        absolute = body['absolute_magnitude_h']
133

134
        # Finally printing the extracted data in a readable format
135
        print(id, name, absolute)
136

137
    print("\nID & Name of those asteroids are listed above.\n")
138

139
# Function which gives information about different solar bodies
140

141

142
def SolarBodies():
143
    print("\nExtracting data.....\n")
144
    print("\nPlease wait.....\n")
145

146
    # Link of the website to fetch data of different bodies of the solar system
147
    url = "https://api.le-systeme-solaire.net/rest/bodies/"
148

149
    # Fetching data from the internet
150
    r = requests.get(url)
151
    Data = r.json()  # Save the fetched data after converting into json object
152

153
    # Clear the terminal for the next operation
154
    os.system('cls' if os.name == 'nt' else 'clear')
155
    print('\n🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\n')
156

157
    # Listing the data / parsing the data set
158
    bodies = Data['bodies']
159
    Number = len(bodies)
160
    print(f"\nNumber of bodies in solar system : {Number}")
161

162
    try:
163
        # Getting input from the user
164
        Body = input(
165
            "\nTell me the name of the solar bodies you want to know - ")
166
        while (Body == None):
167
            Body = input("\nPlease enter the valid input - ")
168
        Body = Body.replace(" ", "")
169

170
        print("\nPlease wait......\n")
171

172
        # Fetching data for that body
173
        body = Body
174
        url_2 = f"https://api.le-systeme-solaire.net/rest/bodies/{body}"
175
        rrr = requests.get(url_2)  # Fetchin data from the internet
176
        data = rrr.json()
177

178
        # Listing / parsing the dataset
179
        mass_1 = data['mass']['massValue']
180
        mass = mass_1*1000  # Converting mass into the trillion tons unit
181
        volume = data['vol']['volValue']
182
        density = data['density']
183
        gravity = data['gravity']
184
        escape = data['escape']
185
        radius = data['meanRadius']
186
        avgTemp = data['avgTemp']
187
        str = data['bodyType']
188

189
        # Displaying the fetched data set in a readable / understandable format
190
        print(
191
            f"\n------------------------------- Data of {body} -------------------------------------")
192
        print(f"\n       Mass of {body} - {mass} trillion tons")
193
        print(f"\n       Volume of {body} - {volume} trillion kilometer^cube")
194
        print(
195
            f"\n       Gravity of {body} - {gravity} meter per second^square")
196
        print(
197
            f"\n       Escape Velocity of {body} - {escape} meter per second")
198
        print(
199
            f"\n       Density of {body} - {density} gram per centimeter^cube")
200
        print(f"\n       Radius of {body} - {radius} kilometer")
201
        print(f"\n       Average Temperature of {body} - {avgTemp} Kelvin")
202
        print(f"\n       Body Type of {body} - {str}")
203
        print(f"\n-----------------------------------------------------------------------------------\n")
204
    except:
205
        print(f"\nData of {body} is not found!\n")
206

207
# Function which fetch the images of different solar bodies
208

209

210
def solarBodiesPictures():
211
    # List of different images for displaying to the user
212
    # Keys of Google drive images
213
    imageKeys = [
214
        '1rktYDEGz0Y95PmN1sJlp0oWchznNBxFY',
215
        '18p1HDuJzf_0Xa-70pHm7okK_ZtcfnPs3',
216
        '1uc85CRZD9m_K5N3sZHh97l9laas9y5yd',
217
        '1zFsOQ3vca-x-UhUK7hzxdAQzuJ0tGIWr',
218
        '1Ae8zekmbQ7fhFA5ZpCSNVwnuBdDSLtxt',
219
        '1K6O-xQPz5G35pEtaYdjkRHdpk0ZtOTSd',
220
        '1SzvHL_E8uA7Hq7D3SDmIAmuaGyzpc4I_',
221
        '1WUn2Kq0iBnmajNHOggIAwt-nhefhZGOM',
222
        '16KhTjl3Mw9LZ-3Ed2Mic4E2HCb6KteZW',
223
        '1taq_Q1JjWKQqrWLB5Fpuhm1Utl8v0wtl',
224
        '1uySzU1yyDv5aQF9YEFcYQwUcmOlFV-j9',
225
        '1Sj0CtJ_kHbM03geTs-FmKPj5IBafdfyP',
226
        '1rgSN5kjGR_iR5w0vqAUDEEZbWctzn_dE',
227
        '1_zAN7M2pfw0tF5Lss453gjC41HZcxI74',
228
        '1Pa_x3o4FcYbnGyC2nibMYhg-ZGr-0EtC',
229
        '1mPlEp4Okgqad001RnOsjvSMyVZiKBFqY',
230
        '1PmBullQHcZhmP1ook9NKkYVaO9_vI1KH',
231
        '1dFXMnIePv6SgPtHKJNhllHd6o25IaUFO',
232
        '1eNJlTy5_MHaFMdH4FSXxwhGXsDriZmTF',
233
        '1wxokZjLeJKRufBwlzCqnTGVOi9Oj8D5v',
234
        '1urlYip6h0-su85TdWqa0vaXrOtEptbHD',
235
        '1j7jWkVihd2VFcr0C-FcKTFqptLu6cbwQ',
236
        '1IYcfhxtr02mYNAAjt1cpa196LDSBO3H-',
237
        '1zNQwgjG-_pBsDuvgXyjndA0ld51LQD1i',
238
        '1HktS1ginfv2QWOjLINa_r5IXJIv-nE_I'
239
    ]
240

241
    print("Extracting data.....\n")
242
    # Selecting a random image key
243
    imageKey = random.choice(imageKeys)
244
    imageURL = f'https://drive.google.com/uc?export=view&id={imageKey}'
245

246
    # Fetch the image content
247
    response = requests.get(imageURL)
248
    image_content = response.content
249

250
    # Load the image using PIL
251
    image = Image.open(io.BytesIO(image_content))
252

253
    print('\nLoading image.....\n')
254
    # Display the image
255
    plt.figure()
256
    plt.imshow(image)
257
    plt.axis('off')
258
    plt.show()
259

260
# This function will tells about the current news of space with images
261

262

263
def todayNews():
264
    nasa = nasapy.Nasa(key=Api_Key)
265

266
    # Get today's date in YYYY-MM-DD format:
267
    d = input("Enter date {yyyy-mm-dd}: ")
268

269
    print('\nExtracting data....\n')
270
    print('\nPlease wait.....\n')
271

272
    # Get the image data:
273
    apod = nasa.picture_of_the_day(date=d, hd=True)
274

275
    # POINT A:
276
    # Check the media type available:
277
    if (apod["media_type"] == "image"):
278

279
        # POINT B:
280
        # Displaying hd images only:
281
        if ("hdurl" in apod.keys()):
282

283
            # POINT C:
284
            # Saving name for image:
285
            title = d + "_" + \
286
                apod["title"].replace(" ", "_").replace(":", "_") + ".jpg"
287

288
            # POINT D:
289
            # Path of the directory:
290
            image_dir = "./"
291

292
            # Checking if the directory already exists?
293
            dir_res = os.path.exists(image_dir)
294

295
            # If it doesn't exist then make a new directory:
296
            if (dir_res == False):
297
                os.makedirs(image_dir)
298

299
            # POINT E:
300
            # Retrieving the image:
301
            urllib.request.urlretrieve(
302
                url=apod["hdurl"], filename=os.path.join(image_dir, title))
303

304
            # Clear the terminal for the next operation
305
            os.system('cls' if os.name == 'nt' else 'clear')
306
            print('\n🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\n')
307

308
            # POINT F:
309
            # Displaying information related to image:
310
            if ("date" in apod.keys()):
311
                print("Date image released: ", apod["date"])
312
                print("\n")
313

314
            if ("copyright" in apod.keys()):
315
                print("This image is owned by: ", apod["copyright"])
316
                print("\n")
317

318
            if ("title" in apod.keys()):
319
                print("Title of the image: ", apod["title"])
320
                print("\n")
321

322
            if ("explanation" in apod.keys()):
323
                print("Description for the image: ", apod["explanation"])
324
                print("\n")
325

326
            if ("hdurl" in apod.keys()):
327
                print("URL for this image: ", apod["hdurl"])
328
                print("\n")
329

330
            # POINT G:
331
            # Displaying main image:
332
            img = Image.open(os.path.join(image_dir, title))
333
            img.show()
334

335
            # Point H:
336
            # Text to Speech Conversion:
337
            # Take input from user:
338
            choice = input("\nPress * to hear the audio explanation : ")
339
            if (choice == "*"):
340
                # Text to be converted:
341
                mytext = apod["explanation"]
342

343
                # Creating an object:
344
                myobj = gTTS(text=mytext, lang="en", slow=False)
345

346
                # Generating audio file name:
347
                audio_title = d + "_" + apod["title"] + ".mp3"
348

349
                # Save the converted file:
350
                myobj.save(os.path.join(image_dir, audio_title))
351

352
                # Name of sound file:
353
                sound_file = os.path.join(image_dir, audio_title)
354

355
                # Playing the converted file
356
                display.display(display.Audio(sound_file, autoplay=True))
357

358
                playsound(f'.\\{audio_title}')
359

360
    # POINT I:
361
    # If media type is not image:
362
    else:
363
        print("\nSorry, Image not available!\n")
364
        time.sleep(2)
365

366
# Function which keeps holding all the other functions
367

368

369
def SpaceNews():
370
    while True:
371
        os.system('cls' if os.name == 'nt' else 'clear')
372

373
        print('''
374
🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀 WELCOME TO SPACE AI CHAT MODEL 🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀
375
                                               (By Avdhesh Varshney)
376
                                        (https://github.com/Avdhesh-Varshney)
377

378
                                            1. Today space news
379
                                            2. Any other day of space news
380
                                            3. Display mars images
381
                                            4. Display data of asteroids
382
                                            5. About any solar bodies
383
                                            6. Pictures of solar bodies
384

385
                                            0. To exit the program
386

387
🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀
388
        ''')
389

390
        choice = input("Please enter your choice: ")
391
        while choice.isdigit() == False:
392
            choice = input("\nPlease enter value in the range [0-6] - ")
393
        choice = int(choice)
394

395
        # Clear the terminal for the next operation
396
        os.system('cls' if os.name == 'nt' else 'clear')
397
        print('\n🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\n')
398

399
        if choice == 0:
400
            print("Thanks for coming !")
401
            print('\n🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\n')
402
            time.sleep(2)
403
            exit()
404

405
        elif choice == 1:
406
            todayNews()
407

408
        elif choice == 2:
409
            spaceNews()
410

411
        elif choice == 3:
412
            MarsImage()
413

414
        elif choice == 4:
415
            Astro()
416

417
        elif choice == 5:
418
            SolarBodies()
419

420
        elif choice == 6:
421
            solarBodiesPictures()
422

423
        else:
424
            print("\nYou have entered the wrong choice !\n")
425

426
        print('\n🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀🚀\n')
427
        input('\nPress "Enter" key to proceed further...\n')
428

429

430
# Program starts
431
SpaceNews()
432

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.