-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpoly_cli.py
More file actions
1323 lines (1124 loc) · 51.6 KB
/
poly_cli.py
File metadata and controls
1323 lines (1124 loc) · 51.6 KB
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests
import sys
import urllib.parse
import argparse
from halo import Halo
from datetime import datetime
from datetime import datetime, timedelta
import sqlite3
from dateutil import parser as dateutil_parser # Renamed to avoid naming conflict
import sqlite3 # Ensure sqlite3 is imported to use its constants
import os
from gnews import GNews
import json
import math
from simple_salesforce import Salesforce, SalesforceAuthenticationFailed, SalesforceExpiredSession
# Parse command-line arguments
parser = argparse.ArgumentParser(description='Poly CLI - A multi-function command-line interface')
parser.add_argument('--debug', action='store_true', help='Enable debug mode with additional information')
args = parser.parse_args()
# Global debug flag
DEBUG_MODE = args.debug
# Global variables to store Salesforce credentials
sf_username = None
sf_password = None
sf_token = None
sf_instance = None
# Adapters for storing and retrieving datetime objects with SQLite
def adapt_datetime_iso(val):
"""Adapt datetime.datetime to ISO 8601 string."""
return val.isoformat()
def convert_datetime_iso(val):
"""Convert ISO 8601 string to datetime.datetime object."""
return datetime.fromisoformat(val.decode())
sqlite3.register_adapter(datetime, adapt_datetime_iso)
sqlite3.register_converter("DATETIME", convert_datetime_iso)
def init_db():
conn = sqlite3.connect('history.db', detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS searches
(id INTEGER PRIMARY KEY AUTOINCREMENT,
address TEXT,
matched_address TEXT,
lat REAL,
lon REAL,
timestamp DATETIME)''')
c.execute('''CREATE TABLE IF NOT EXISTS news_sites
(id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT UNIQUE,
timestamp DATETIME)''')
conn.commit()
conn.close()
def save_search(address, location_data):
conn = sqlite3.connect('history.db', detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
c = conn.cursor()
c.execute('''INSERT INTO searches (address, matched_address, lat, lon, timestamp)
VALUES (?, ?, ?, ?, ?)''',
(address,
location_data['matched_address'],
location_data['lat'],
location_data['lon'],
datetime.now()))
conn.commit()
conn.close()
def save_news_site(url):
"""Save a news site URL to the database"""
conn = sqlite3.connect('history.db', detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
c = conn.cursor()
try:
c.execute('''INSERT OR IGNORE INTO news_sites (url, timestamp)
VALUES (?, ?)''', (url, datetime.now()))
conn.commit()
except sqlite3.Error as e:
print(f"Database error: {e}")
finally:
conn.close()
def get_saved_news_sites():
"""Get all saved news site URLs from the database"""
conn = sqlite3.connect('history.db', detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
c = conn.cursor()
c.execute('''SELECT url FROM news_sites ORDER BY timestamp DESC''')
sites = [row[0] for row in c.fetchall()]
conn.close()
return sites
def get_coordinates(address):
"""Convert address to coordinates using Census Geocoding API"""
encoded_address = urllib.parse.quote(address)
census_url = f"https://geocoding.geo.census.gov/geocoder/locations/onelineaddress?address={encoded_address}&benchmark=2020&format=json"
spinner = Halo('Looking up address...')
spinner.start()
try:
response = requests.get(census_url)
response.raise_for_status()
data = response.json()
if data['result']['addressMatches']:
match = data['result']['addressMatches'][0]
return {
'lat': match['coordinates']['y'],
'lon': match['coordinates']['x'],
'matched_address': match['matchedAddress']
}
else:
return None
except Exception as e:
print(f"Error getting coordinates: {e}")
return None
finally:
spinner.stop()
def get_weather(lat, lon):
"""Get weather data from National Weather Service API"""
spinner = Halo('Getting weather data...')
spinner.start()
try:
# First, get the grid coordinates
point_url = f"https://api.weather.gov/points/{lat},{lon}"
response = requests.get(point_url)
response.raise_for_status()
grid_data = response.json()
# Then get the forecast data using the grid coordinates
forecast_url = grid_data['properties']['forecast']
response = requests.get(forecast_url)
response.raise_for_status()
weather_data = response.json()
current_period = weather_data['properties']['periods'][0]
forecast_periods = weather_data['properties']['periods'][1:4] # Next 3 periods
return {
'current': {
'temperature': current_period['temperature'],
'unit': current_period['temperatureUnit'],
'forecast': current_period['shortForecast'],
'wind': current_period['windSpeed'] + ' ' + current_period['windDirection'],
'humidity': current_period.get('relativeHumidity', {}).get('value', 'N/A'),
},
'forecast': forecast_periods
}
except Exception as e:
print(f"Error getting weather: {e}")
return None
finally:
spinner.stop()
def get_google_maps_url(address):
"""Generate Google Maps URL for the address"""
encoded_address = urllib.parse.quote(address)
return f"https://www.google.com/maps/search/?api=1&query={encoded_address}"
def display_weather(location_data, weather_data):
"""Display weather results"""
maps_url = get_google_maps_url(location_data['matched_address'])
print("\nResults:")
print(f"Matched Address: {location_data['matched_address']}")
print("\nCurrent Conditions:")
print(f"Temperature: {weather_data['current']['temperature']}°{weather_data['current']['unit']}")
print(f"Conditions: {weather_data['current']['forecast']}")
print(f"Wind: {weather_data['current']['wind']}")
if weather_data['current']['humidity'] != 'N/A':
print(f"Humidity: {weather_data['current']['humidity']}%")
print("\nUpcoming Forecast:")
for period in weather_data['forecast']:
print(f"\n{period['name']}:")
print(f" Temperature: {period['temperature']}°{period['temperatureUnit']}")
print(f" Conditions: {period['shortForecast']}")
print(f" Wind: {period['windSpeed']} {period['windDirection']}")
print(f"\nView on Google Maps: {maps_url}")
def lookup_weather():
"""Handle weather lookup logic"""
address = safe_input("\nEnter address (street, city, state, zip code): ")
# Get coordinates
spinner = Halo('Looking up address...')
spinner.start()
location_data = get_coordinates(address)
spinner.stop()
if location_data is None:
print("\nError: Could not find the address. Please check and try again.")
return
# Get weather
weather_data = get_weather(location_data['lat'], location_data['lon'])
if weather_data is None:
print("\nError: Could not retrieve weather data.")
return
display_weather(location_data, weather_data)
if location_data:
save_search(address, location_data)
def get_saved_addresses():
conn = sqlite3.connect('history.db', detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
c = conn.cursor()
c.execute('''SELECT DISTINCT address, matched_address, lat, lon, MAX(timestamp) as latest
FROM searches
GROUP BY matched_address
ORDER BY latest DESC''')
addresses = c.fetchall()
conn.close()
return addresses
def select_saved_address():
addresses = get_saved_addresses()
if not addresses:
print("\nNo saved addresses found.")
return
print("\nSaved addresses:")
for i, (address, matched_address, lat, lon, _) in enumerate(addresses, 1):
print(f"{i}. {matched_address}")
choice = safe_input("\nSelect address number (or 0 to go back): ")
try:
choice = int(choice)
if choice == 0:
return
if 1 <= choice <= len(addresses):
_, matched_address, lat, lon, _ = addresses[choice-1]
location_data = {
'matched_address': matched_address,
'lat': lat,
'lon': lon
}
weather_data = get_weather(lat, lon)
if weather_data:
display_weather(location_data, weather_data)
safe_input("\nPress Enter to continue...")
else:
print("\nInvalid selection.")
except ValueError:
print("\nPlease enter a valid number.")
def weather_menu():
"""Display and handle weather submenu"""
while True:
try:
print("\n=== Weather Lookup Menu ===")
print("1. Enter new address")
print("2. Select from saved addresses")
print("3. Return to main menu")
choice = safe_input("\nEnter your choice (1-3): ")
if choice == "1":
lookup_weather()
elif choice == "2":
select_saved_address()
elif choice == "3":
return
else:
print("\nInvalid choice. Please enter 1-3.")
except KeyboardInterrupt:
exit_gracefully("\n\nProgram interrupted. Goodbye!")
except EOFError:
exit_gracefully("\n\nEnd of input. Goodbye!")
def get_sports_scores(sport, league, league_name):
"""Fetch sports scores from ESPN API for specified league"""
spinner = Halo(f'Getting {league_name} scores...')
spinner.start()
try:
url = f"https://site.api.espn.com/apis/site/v2/sports/{sport}/{league}/scoreboard"
response = requests.get(url)
response.raise_for_status()
data = response.json()
if not data.get('events'):
print(f"\nNo {league_name} games found.")
# Show debug info only when in debug mode
if DEBUG_MODE:
print(f"\n--- Debug Info ---")
print(f"API URL: {url}")
print(f"Data returned: {json.dumps(data, indent=2, default=str)[:500]}...") # Show truncated data
print("-" * 70)
return
print(f"\n{league_name} Scores:")
print("-" * 50)
for event in data['events']:
game_status = event['status']['type']['state']
competition = event['competitions'][0]
home_team = competition['competitors'][0]
away_team = competition['competitors'][1]
# Get venue information if available (for all game states)
venue_info = ""
if competition.get('venue') and competition['venue'].get('fullName'):
venue_name = competition['venue']['fullName']
# Get city/state if available
if competition['venue'].get('address') and competition['venue']['address'].get('city'):
venue_city = competition['venue']['address']['city']
venue_info = f"{venue_name}, {venue_city}"
else:
venue_info = venue_name
# Format based on game status
if game_status == 'pre':
# Use the detail field which contains the game time in local timezone
# Detail example: "Sat, May 24th at 3:00 PM EDT"
game_time = event['status']['type'].get('detail', event['status']['type'].get('shortDetail', 'Scheduled'))
print(f"{away_team['team']['displayName']} @ {home_team['team']['displayName']}")
print(f"Starting: {game_time}")
else:
home_score = home_team['score']
away_score = away_team['score']
if game_status == 'in':
period = event['status']['type']['shortDetail']
print(f"{away_team['team']['displayName']} {away_score} @ {home_team['team']['displayName']} {home_score}")
print(f"Current: {period}")
else: # post-game
print(f"Final: {away_team['team']['displayName']} {away_score} @ {home_team['team']['displayName']} {home_score}")
# Display venue info for all game states
if venue_info.strip():
print(f"Venue: {venue_info.strip()}")
print("-" * 70)
# Display debug info only in debug mode
if DEBUG_MODE:
print(f"--- Debug Info ---")
print(f"API URL: {url}")
# For MLS, show extra debug info about the response structure
if league == "usa.1" and data.get('events'):
print("\nMLS Debug: Sample event structure")
sample_event = data['events'][0]
print(f"Event date format: {sample_event.get('date', 'N/A')}")
print(f"Status type: {json.dumps(sample_event.get('status', {}).get('type', {}), indent=2, default=str)}")
print(f"League: {json.dumps(data.get('leagues', [{}])[0] if data.get('leagues') else {}, indent=2, default=str)[:200]}...")
except Exception as e:
print(f"\nError getting {league_name} scores: {e}")
# Display debug info for troubleshooting even when there's an error, but only in debug mode
if DEBUG_MODE:
print(f"\n--- Debug Info ---")
print(f"API URL: {url}")
print("-" * 70)
finally:
spinner.stop()
safe_input("\nPress Enter to continue...")
def get_nfl_scores():
"""Fetch NFL scores from ESPN API (legacy function for compatibility)"""
get_sports_scores("football", "nfl", "NFL")
def scores_menu():
"""Display and handle sports scores menu"""
while True:
try:
print("\n=== Sports Scores Menu ===")
print("1. NFL")
print("2. MLB")
print("3. NHL")
print("4. NBA")
print("5. MLS")
print("6. College Football")
# Conditionally add the debug option
if DEBUG_MODE:
print("7. View Raw API Data")
print("8. Return to main menu")
max_option = 8
else:
print("7. Return to main menu")
max_option = 7
choice = safe_input(f"\nEnter your choice (1-{max_option}): ")
if choice == "1":
get_sports_scores("football", "nfl", "NFL")
elif choice == "2":
get_sports_scores("baseball", "mlb", "MLB")
elif choice == "3":
get_sports_scores("hockey", "nhl", "NHL")
elif choice == "4":
get_sports_scores("basketball", "nba", "NBA")
elif choice == "5":
get_sports_scores("soccer", "usa.1", "MLS")
elif choice == "6":
get_sports_scores("football", "college-football", "NCAA Football")
elif choice == "7" and DEBUG_MODE:
view_raw_sports_data_menu()
elif (choice == "7" and not DEBUG_MODE) or (choice == "8" and DEBUG_MODE):
return
else:
print(f"\nInvalid choice. Please enter 1-{max_option}.")
except KeyboardInterrupt:
exit_gracefully("\n\nProgram interrupted. Goodbye!")
except EOFError:
exit_gracefully("\n\nEnd of input. Goodbye!")
def view_raw_sports_data(sport, league, league_name):
"""View raw JSON data from the ESPN API for a specific league"""
spinner = Halo(f'Fetching raw {league_name} API data...')
spinner.start()
try:
url = f"https://site.api.espn.com/apis/site/v2/sports/{sport}/{league}/scoreboard"
response = requests.get(url)
response.raise_for_status()
data = response.json()
spinner.stop()
print(f"\n=== Raw {league_name} API Data ===")
print(f"API URL: {url}")
print("\nJSON Response (first 1000 characters):")
print("-" * 80)
print(json.dumps(data, indent=2, default=str)[:1000])
print("...")
print("-" * 80)
# Show important sections of the data structure
if data.get('events'):
print("\nImportant Data Fields:")
print("-" * 80)
print(f"Number of events: {len(data['events'])}")
if len(data['events']) > 0:
sample_event = data['events'][0]
print(f"\nSample Event ID: {sample_event.get('id', 'N/A')}")
print(f"Event Date: {sample_event.get('date', 'N/A')}")
print(f"Status State: {sample_event.get('status', {}).get('type', {}).get('state', 'N/A')}")
print(f"Status Detail: {sample_event.get('status', {}).get('type', {}).get('shortDetail', 'N/A')}")
else:
print("\nNo events found in the API response.")
except Exception as e:
spinner.fail(f"Error fetching {league_name} data: {e}")
print("\n")
safe_input("Press Enter to continue...")
def view_raw_sports_data_menu():
"""Display and handle raw sports data menu"""
while True:
try:
print("\n=== View Raw Sports Data Menu ===")
print("1. NFL")
print("2. MLB")
print("3. NHL")
print("4. NBA")
print("5. MLS")
print("6. College Football")
print("7. Return to sports scores menu")
choice = safe_input("\nEnter your choice (1-7): ")
if choice == "1":
view_raw_sports_data("football", "nfl", "NFL")
elif choice == "2":
view_raw_sports_data("baseball", "mlb", "MLB")
elif choice == "3":
view_raw_sports_data("hockey", "nhl", "NHL")
elif choice == "4":
view_raw_sports_data("basketball", "nba", "NBA")
elif choice == "5":
view_raw_sports_data("soccer", "usa.1", "MLS")
elif choice == "6":
view_raw_sports_data("football", "college-football", "NCAA Football")
elif choice == "7":
return
else:
print("\nInvalid choice. Please enter 1-7.")
except KeyboardInterrupt:
exit_gracefully("\n\nProgram interrupted. Goodbye!")
except EOFError:
exit_gracefully("\n\nEnd of input. Goodbye!")
# Keep this for backward compatibility
def nfl_menu():
"""Redirects to the scores menu for backward compatibility"""
scores_menu()
def get_news(domain=None):
"""Fetch news articles using GNews"""
spinner = Halo('Fetching news articles...')
spinner.start()
try:
# Initialize GNews with default settings
google_news = GNews(language='en', country='US', period='1d', max_results=5)
# Set default domain to wsj.com if none provided
domain = domain or 'wsj.com'
# Use the correct method to fetch articles by site
articles = google_news.get_news_by_site(domain)
if not articles:
print(f"\nNo articles found for domain: {domain}")
return False
print(f"\nLatest news from {domain}:")
print("-" * 80)
for article in articles:
# Parse and format the date
pub_date = dateutil_parser.parse(article['published date'])
friendly_date = pub_date.strftime("%B %d, %Y at %I:%M %p")
print(f"Title: {article['title']}")
print(f"Published: {friendly_date}")
print(f"URL: {article['url']}")
print("-" * 80)
# Save the domain to database if successful
save_news_site(domain)
return True
except Exception as e:
print(f"\nUnexpected error: {e}")
finally:
spinner.stop()
safe_input("\nPress Enter to continue...")
def news_menu():
"""Display and handle news menu"""
# Default news sites to include
default_sites = ['wsj.com', 'washingtonpost.com', 'nytimes.com', 'apnews.com']
# Initialize default news sites in the database if they don't exist
for site in default_sites:
save_news_site(site)
while True:
try:
# Get saved news sites from database
all_sites = get_saved_news_sites()
# Separate default sites from user-saved sites
user_saved_sites = [site for site in all_sites if site not in default_sites]
print("\n=== News Menu ===")
# Display default news sites section
print("=== Default News Sites ===")
next_index = 1
for i, site in enumerate(default_sites, next_index):
print(f"{i}. {site}")
next_index += len(default_sites)
# Display user-saved news sites section, if any
if user_saved_sites:
print("\n=== Saved News Sites ===")
for i, site in enumerate(user_saved_sites, next_index):
print(f"{i}. {site}")
next_index += len(user_saved_sites)
# Add options at the bottom
print("\n=== Options ===")
print(f"{next_index}. Enter a new domain")
print(f"{next_index + 1}. Return to main menu")
# Calculate total options
total_options = next_index + 1
choice = safe_input(f"\nEnter your choice (1-{total_options}): ")
try:
choice_num = int(choice)
if 1 <= choice_num < 1 + len(default_sites):
# User selected a default site
selected_site = default_sites[choice_num - 1]
get_news(selected_site)
elif 1 + len(default_sites) <= choice_num < 1 + len(default_sites) + len(user_saved_sites):
# User selected a saved site
selected_site = user_saved_sites[choice_num - (1 + len(default_sites))]
get_news(selected_site)
elif choice_num == total_options - 1:
# User selected "Enter a new domain"
domain = safe_input("\nEnter domain (e.g., wsj.com): ")
if domain:
get_news(domain)
elif choice_num == total_options:
# User selected "Return to main menu"
return
else:
print(f"\nInvalid choice. Please enter 1-{total_options}.")
except ValueError:
print("\nInvalid input. Please enter a number.")
except KeyboardInterrupt:
exit_gracefully("\n\nProgram interrupted. Goodbye!")
except EOFError:
exit_gracefully("\n\nEnd of input. Goodbye!")
def get_bls_data(series_id):
"""Fetch data from BLS API for a given series ID"""
url = f"https://api.bls.gov/publicAPI/v2/timeseries/data/{series_id}"
headers = {'Content-type': 'application/json'}
data = json.dumps({
"seriesid": [series_id],
"startyear": "2022",
"endyear": "2023"
})
response = requests.post(url, headers=headers, data=data)
response.raise_for_status()
return response.json()
def display_bls_data():
"""Display economic indicators from BLS API"""
# Removed global spinner initialization and start
series_ids = {
"CPI": "CUSR0000SA0",
"CPI Less Food and Energy": "CUSR0000SA0L1E",
"PPI": "PCUOMFG--OMFG--",
"Nonfarm Payroll": "CES0000000001",
"Unemployment Rate": "LNS14000000",
"Employment in Residential Construction": "CES2023610001"
}
for name, series_id in series_ids.items():
spinner = Halo(text=f'Fetching {name}...', spinner='dots')
spinner.start()
try:
data = get_bls_data(series_id) # This function calls response.raise_for_status()
if 'Results' not in data or not data['Results'] or \
'series' not in data['Results'] or not data['Results']['series'] or \
'data' not in data['Results']['series'][0] or not data['Results']['series'][0]['data']:
spinner.fail(f"Failed to fetch {name}: Unexpected data structure or empty series data.")
print(f"\n{name}: Unexpected data structure or empty series data received.")
continue
series_data = data['Results']['series'][0]['data']
if len(series_data) < 2:
spinner.warn(f"Insufficient data for {name}")
print(f"\n{name}: No sufficient data available (requires at least 2 data points for comparison).")
continue
latest_data = series_data[0]
previous_data = series_data[1]
latest_value = float(latest_data['value'])
previous_value = float(previous_data['value'])
year = latest_data['year']
period = latest_data['periodName']
percentage_change = ((latest_value - previous_value) / previous_value) * 100
spinner.succeed(f'Successfully fetched {name}')
print(f"\n{name}:")
print(f" Value: {latest_value}")
print(f" Date: {period} {year}")
print(f" Month-over-Month Change: {percentage_change:.2f}%")
except requests.exceptions.HTTPError as e:
spinner.fail(f'Failed to fetch {name}')
error_message = f"HTTP {e.response.status_code} - {e.response.reason}"
try: # Try to get more specific error from BLS response
error_details = e.response.json().get('message')
if error_details:
error_message += f": {', '.join(error_details)}"
except ValueError: # If response is not JSON or no 'message' field
pass
print(f"\nError fetching {name}: {error_message}")
except Exception as e:
spinner.fail(f'Failed to process {name}')
print(f"\nError processing {name}: {e}")
# Removed global spinner stop from a finally block
safe_input("\nPress Enter to continue...")
def bls_menu():
"""Display and handle BLS data menu"""
while True:
try:
print("\n=== BLS Economic Indicators Menu ===")
print("1. View latest economic indicators")
print("2. Return to main menu")
choice = safe_input("\nEnter your choice (1-2): ")
if choice == "1":
display_bls_data()
elif choice == "2":
return
else:
print("\nInvalid choice. Please enter 1-2.")
except KeyboardInterrupt:
exit_gracefully("\n\nProgram interrupted. Goodbye!")
except EOFError:
exit_gracefully("\n\nEnd of input. Goodbye!")
def extract_state(matched_address):
"""Extract the state from the matched address"""
address_parts = matched_address.split(',')
state = address_parts[-2].strip() # Assuming state is the second-to-last part
return state
def haversine_distance(lat1, lon1, lat2, lon2):
"""Calculate the distance between two points on a sphere using the Haversine formula"""
R = 6371 # Radius of the Earth in kilometers
lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
dlat = lat2 - lat1
dlon = lon2 - lon1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
distance = R * c
return distance
def get_nearest_station(address_data):
"""Find the nearest NOAA tide station using metadata API"""
url = f"https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations.json?format=json"
response = requests.get(url)
response.raise_for_status()
data = response.json()
# Extract the state from the address data
state = extract_state(address_data['matched_address'])
# Manually filter the results to find the stations in the state
state_stations = [station for station in data['stations'] if station['state'] == state]
# Calculate the distance between each station and the street address
nearest_station = None
min_distance = float('inf')
for station in state_stations:
station_lat = float(station['lat'])
station_lon = float(station.get('lon', station.get('lng'))) # Handle both 'lon' and 'lng' keys
distance = haversine_distance(address_data['lat'], address_data['lon'], station_lat, station_lon)
if distance < min_distance:
min_distance = distance
nearest_station = station['id']
return nearest_station
def get_tide_data(station_id):
"""Fetch tide data from NOAA API for a given station ID"""
today = datetime.today().strftime("%Y%m%d")
tomorrow = (datetime.today() + timedelta(days=1)).strftime("%Y%m%d")
url = f"https://api.tidesandcurrents.noaa.gov/api/prod/datagetter"
params = {
"product": "predictions",
"application": "NOS.COOPS.TAC.WL",
"begin_date": f"{today}",
"end_date": f"{tomorrow}",
"datum": "MLLW",
"station": station_id,
"time_zone": "lst_ldt",
"units": "english",
"interval": "hilo",
"format": "json"
}
response = requests.get(url, params=params)
response.raise_for_status()
return response.json()
def display_tide_data(tide_data):
"""Display tide information"""
print("\nTide Information:")
for prediction in tide_data['predictions']:
time = datetime.strptime(prediction['t'], "%Y-%m-%d %H:%M")
tide_type = "High Tide" if prediction['type'] == "H" else "Low Tide"
formatted_time = time.strftime("%I:%M %p, %A, %B %d, %Y")
print(f"{formatted_time} - {tide_type}")
def display_station_info(station_info):
"""Display station information"""
print("\nStation Information:")
print(f"Station ID: {station_info['stations'][0]['id']}")
print(f"Station Name: {station_info['stations'][0]['name']}")
print(f"State: {station_info['stations'][0]['state']}")
print(f"Latitude: {station_info['stations'][0]['lat']}")
print(f"Longitude: {station_info['stations'][0]['lng']}")
# Generate Google Maps URL
google_maps_url = f"https://www.google.com/maps/@?api=1&map_action=map¢er={station_info['stations'][0]['lat']},{station_info['stations'][0]['lng']}&zoom=15"
print("Google Maps:")
print(google_maps_url)
def get_station_info(station_id):
"""Fetch station information from NOAA API"""
url = f"https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations/{station_id}.json"
response = requests.get(url)
response.raise_for_status()
return response.json()
def lookup_tides():
"""Handle tide lookup logic"""
address = safe_input("\nEnter address (street, city, state, zip code): ")
# Get coordinates
location_data = get_coordinates(address)
if location_data is None:
print("\nError: Could not find the address. Please check and try again.")
return
# Display matched address
print("\nMatched Address:")
print("-" * 50)
print(f"Street: {location_data['matched_address'].split(',')[0]}")
print(f"City: {location_data['matched_address'].split(',')[1].strip()}")
print(f"State: {location_data['matched_address'].split(',')[2].strip()}")
print(f"Zip Code: {location_data['matched_address'].split(',')[3].strip()}")
print(f"Latitude: {location_data['lat']}")
print(f"Longitude: {location_data['lon']}")
# Generate Google Maps URL
google_maps_url = f"https://www.google.com/maps/@?api=1&map_action=map¢er={location_data['lat']},{location_data['lon']}&zoom=15"
print(f"\nClick to view matched address on Google Maps: {google_maps_url}")
# Get nearest station
station_id = get_nearest_station(location_data)
if station_id is None:
print("\nError: Could not find a nearby tide station.")
return
# Get station information
station_info = get_station_info(station_id)
if station_info is None:
print("\nError: Could not retrieve station information.")
return
# Display station information
display_station_info(station_info)
# Get tide data
try:
tide_data = get_tide_data(station_id)
# Save the address to the database since we successfully got tide data
save_search(address, location_data)
except requests.exceptions.HTTPError as e:
print(f"\nError: Failed to retrieve tide data. {e}")
return
# Display tide data
display_tide_data(tide_data)
def select_saved_address_for_tides():
"""Handle selecting a saved address for tide lookup"""
addresses = get_saved_addresses()
if not addresses:
print("\nNo saved addresses found.")
return
print("\nSaved addresses:")
for i, (address, matched_address, lat, lon, _) in enumerate(addresses, 1):
print(f"{i}. {matched_address}")
choice = safe_input("\nSelect address number (or 0 to go back): ")
try:
choice = int(choice)
if choice == 0:
return
if 1 <= choice <= len(addresses):
_, matched_address, lat, lon, _ = addresses[choice-1]
location_data = {
'matched_address': matched_address,
'lat': lat,
'lon': lon
}
# Get nearest station
station_id = get_nearest_station(location_data)
if station_id is None:
print("\nError: Could not find a nearby tide station.")
return
# Get station information
station_info = get_station_info(station_id)
if station_info is None:
print("\nError: Could not retrieve station information.")
return
# Display station information
display_station_info(station_info)
# Get tide data
try:
tide_data = get_tide_data(station_id)
# Display tide data
display_tide_data(tide_data)
except requests.exceptions.HTTPError as e:
print(f"\nError: Failed to retrieve tide data. {e}")
return
safe_input("\nPress Enter to continue...")
else:
print("\nInvalid selection.")
except ValueError:
print("\nPlease enter a valid number.")
def tides_menu():
"""Display and handle tides menu"""
while True:
try:
print("\n=== Tides Menu ===")
print("1. Enter new address")
print("2. Select from saved addresses")
print("3. Return to main menu")
choice = safe_input("\nEnter your choice (1-3): ")
if choice == "1":
lookup_tides()
elif choice == "2":
select_saved_address_for_tides()
elif choice == "3":
return
else:
print("\nInvalid choice. Please enter 1-3.")
except KeyboardInterrupt:
exit_gracefully("\n\nProgram interrupted. Goodbye!")
except EOFError:
exit_gracefully("\n\nEnd of input. Goodbye!")
def get_salesforce_credentials():
"""Prompt the user for Salesforce credentials and verify them"""
global sf_username, sf_password, sf_token, sf_instance
if sf_instance is not None:
return sf_instance
sf_username_env = os.getenv("SALESFORCE_USERNAME")
sf_password_env = os.getenv("SALESFORCE_PASSWORD")
sf_token_env = os.getenv("SALESFORCE_SECURITY_TOKEN")
if sf_username_env and sf_password_env and sf_token_env:
spinner = Halo('Authenticating with Salesforce using environment variables...')
spinner.start()
try:
sf_instance = Salesforce(username=sf_username_env, password=sf_password_env, security_token=sf_token_env)
spinner.succeed("Salesforce authentication successful using environment variables.")
# Store them globally if needed, or just use the instance
sf_username = sf_username_env
sf_password = sf_password_env # Not strictly necessary to store if only instance is used
sf_token = sf_token_env # Not strictly necessary to store if only instance is used
return sf_instance
except SalesforceAuthenticationFailed:
spinner.fail("Salesforce authentication failed using environment variables.")
print("Please check your SALESFORCE_USERNAME, SALESFORCE_PASSWORD, and SALESFORCE_SECURITY_TOKEN environment variables.")
return None
except Exception as e:
spinner.fail(f"An unexpected error occurred during Salesforce authentication: {e}")
return None
finally:
if 'spinner' in locals():
spinner.stop()
else:
print("\nSalesforce credentials not found in environment variables.")
print("Please set SALESFORCE_USERNAME, SALESFORCE_PASSWORD, and SALESFORCE_SECURITY_TOKEN.")
return None
def query_salesforce_contacts(sf, filter_value):
query = f"""
SELECT Account.Name, FirstName, LastName, Title, Email, Phone, Description
FROM Contact
WHERE Account.Name LIKE '%{filter_value}%'
OR FirstName LIKE '%{filter_value}%'
OR LastName LIKE '%{filter_value}%'
OR Title LIKE '%{filter_value}%'
OR Email LIKE '%{filter_value}%'
"""
try:
contacts = sf.query(query)['records']
except SalesforceExpiredSession:
print("\nSalesforce session expired. Please re-enter your credentials.")
get_salesforce_credentials()
contacts = sf.query(query)['records']