Skip to content

Commit 3d6e148

Browse files
committed
Add initial backend implementation with quote retrieval, weather forecast, and Wikipedia article summary
1 parent 324c4f9 commit 3d6e148

File tree

6 files changed

+282
-0
lines changed

6 files changed

+282
-0
lines changed

start_your_day/.gitignore

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
develop-eggs/
13+
dist/
14+
downloads/
15+
eggs/
16+
.eggs/
17+
lib/
18+
lib64/
19+
parts/
20+
sdist/
21+
var/
22+
wheels/
23+
share/python-wheels/
24+
*.egg-info/
25+
.installed.cfg
26+
*.egg
27+
28+
# PyInstaller
29+
# Usually these files are written by a python script from a template
30+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
31+
*.manifest
32+
*.spec
33+
34+
# Installer logs
35+
pip-log.txt
36+
pip-delete-this-directory.txt
37+
38+
# Unit test / coverage reports
39+
htmlcov/
40+
.tox/
41+
.nox/
42+
.coverage
43+
.coverage.*
44+
.cache
45+
nosetests.xml
46+
coverage.xml
47+
*.cover
48+
*.py,cover
49+
.hypothesis/
50+
51+
# Translations
52+
*.mo
53+
*.pot
54+
55+
# Django stuff:
56+
*.log
57+
local_settings.py
58+
db.sqlite3
59+
db.sqlite3-journal
60+
61+
# Flask stuff:
62+
instance/
63+
.webassets-cache
64+
65+
# Scrapy stuff:
66+
.scrapy
67+
68+
# Sphinx documentation
69+
docs/_build/
70+
71+
# PyBuilder
72+
target/
73+
74+
# Jupyter Notebook
75+
.ipynb_checkpoints
76+
77+
# IPython
78+
profile_default/
79+
ipython_config.py
80+
81+
# pyenv
82+
.python-version
83+
84+
# celery beat schedule file
85+
celerybeat-schedule
86+
87+
# SageMath parsed files
88+
*.sage.py
89+
90+
# Environments
91+
/backend/.env
92+
.venv
93+
env/
94+
venv/
95+
ENV/
96+
env.bak/
97+
venv.bak/
98+
99+
# Spyder project settings
100+
.spyderproject
101+
.spyproject
102+
103+
# Rope project settings
104+
.ropeproject
105+
106+
# mkdocs documentation
107+
/site
108+
109+
# mypy
110+
.mypy_cache/
111+
.dmypy.json
112+
dmypy.json
113+
114+
# Pyre type checker
115+
.pyre/
116+
117+
# pytype static type analyzer
118+
.pytype/
119+
120+
# Cython debug symbols
121+
cython_debug/

start_your_day/backend/content.py

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
import csv
2+
import random
3+
import os
4+
from dotenv import load_dotenv
5+
from urllib import request
6+
import json
7+
import datetime
8+
9+
load_dotenv()
10+
11+
"""
12+
Load a random quote from a CSV file and return it as a dictionary.
13+
"""
14+
def get_random_quote(quotes_file='quotes.csv'):
15+
try: #load the quotes from the csv file
16+
with open(quotes_file, 'r') as file:
17+
quotes = [{'author': line[0], 'quote': line[1]} for line in csv.reader(file, delimiter='|')]
18+
except Exception as e: # if there is an exception, return a default quote
19+
print(f'Error loading quotes: {e}')
20+
quotes = [{'author': 'Unknown', 'quote': 'An error occurred while loading the quotes. Please try again later.'}]
21+
22+
return random.choice(quotes) # return a random quote
23+
24+
"""
25+
Get the weather forecast for a specific location using the OpenWeatherMap API.
26+
"""
27+
def get_weather_forecast(my_coords={'lat': 48.9881, 'lon': 2.2339}):
28+
try:
29+
# Retrieve the weather forecast from the OpenWeatherMap API
30+
api_key = os.getenv('WEATHER_API_KEY') # Get the API key from environment variables
31+
url = f'https://api.openweathermap.org/data/2.5/forecast?lat={my_coords["lat"]}&lon={my_coords["lon"]}&exclude=minutely,hourly&appid={api_key}&units=metric'
32+
response = json.load(request.urlopen(url))
33+
34+
# Process the API response into a clean structure
35+
forecast = {
36+
"city": response['city']['name'],
37+
"country": response['city']['country'],
38+
"forecast": [] # List to store the forecast for the next periods
39+
}
40+
41+
for period in response['list'][:9]: # Get the first 9 forecast periods
42+
forecast['forecast'].append({
43+
'timestamp': datetime.datetime.fromtimestamp(period['dt']).strftime('%Y-%m-%d %H:%M:%S'),
44+
'temperature': period['main']['temp'],
45+
'description': period['weather'][0]['description'].title(),
46+
'icon': f"https://openweathermap.org/img/wn/{period['weather'][0]['icon']}@2x.png"
47+
})
48+
49+
return forecast
50+
51+
except Exception as e:
52+
# Handle errors and return a default structure
53+
print(f'Error loading weather forecast: {e}')
54+
return {
55+
"city": "Unknown",
56+
"country": "Unknown",
57+
"forecast": []
58+
}
59+
60+
"""
61+
Get a random summary of Wikipedia articles.
62+
"""
63+
def get_wikipedia_article():
64+
try:
65+
# Retrieve a random Wikipedia article summary using the Wikipedia API
66+
url = 'https://en.wikipedia.org/api/rest_v1/page/random/summary'
67+
response = json.load(request.urlopen(url))
68+
69+
# Process the API response into a clean structure
70+
article = {
71+
"title": response['title'],
72+
"extract": response['extract'],
73+
"url": response['content_urls']['desktop']['page']
74+
}
75+
76+
return article
77+
78+
except Exception as e:
79+
# Handle errors and return a default structure
80+
print(f'Error loading Wikipedia article: {e}')
81+
return {
82+
"title": "Unknown",
83+
"extract": "An error occurred while loading the Wikipedia article. Please try again later.",
84+
"url": "#"
85+
}
86+
87+
88+
if __name__ == '__main__':
89+
# Test the get_random_quote function
90+
print("Testing the get_random_quote function")
91+
quote = get_random_quote()
92+
print(f"Quote: {quote['quote']}, Author: {quote['author']}")
93+
94+
quote = get_random_quote('quotes2.csv')
95+
print(f"Quote: {quote['quote']} Author: {quote['author']}")
96+
97+
# Test the get_weather_forecast function
98+
print("\nTesting the get_weather_forecast function")
99+
100+
# Test the default location
101+
forecast = get_weather_forecast() # Default location
102+
print(f"City: {forecast['city']}, Country: {forecast['country']}")
103+
for period in forecast['forecast']:
104+
print(f"Timestamp: {period['timestamp']}, Temperature: {period['temperature']}, "
105+
f"Description: {period['description']}, Icon: {period['icon']}")
106+
107+
# Test the get_weather_forecast function with a custom location in Paris
108+
print("\nTesting with a custom location: Paris, France")
109+
forecast = get_weather_forecast({'lat': 48.8566, 'lon': 2.3522}) # Paris, France
110+
print(f"City: {forecast['city']}, Country: {forecast['country']}")
111+
for period in forecast['forecast']:
112+
print(f"Timestamp: {period['timestamp']}, Temperature: {period['temperature']}, "
113+
f"Description: {period['description']}, Icon: {period['icon']}")
114+
115+
# Test the error handling with an invalid location
116+
print("\nTesting with an invalid location: (0, 0)")
117+
forecast = get_weather_forecast({'lat': 0, 'lon': 0}) # Invalid location
118+
print(f"City: {forecast['city']}, Country: {forecast['country']}")
119+
for period in forecast['forecast']:
120+
print(f"Timestamp: {period['timestamp']}, Temperature: {period['temperature']}, "
121+
f"Description: {period['description']}, Icon: {period['icon']}")
122+
123+
# Test the get_wikipedia_article function
124+
print("\nTesting the get_wikipedia_article function")
125+
article = get_wikipedia_article()
126+
print(f"Title: {article['title']}")
127+
print(f"Extract: {article['extract']}")
128+
print(f"URL: {article['url']}")
129+
130+
131+

start_your_day/backend/emails.py

Whitespace-only changes.

start_your_day/backend/gui.py

Whitespace-only changes.

start_your_day/backend/quotes.csv

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
Silverster Stallone, Rocky Balboa, | It ain't about how hard you hit. It's about how hard you can get hit and keep moving forward.
2+
Arnold Schwarzenegger, Terminator, | I'll be back.
3+
Bruce Lee, Enter the Dragon, | Don't think. Feel.
4+
Orson Welles, Citizen Kane, | Rosebud.
5+
Clint Eastwood, Dirty Harry, | Go ahead, make my day.
6+
Marlon Brando, The Godfather, | I'm gonna make him an offer he can't refuse.
7+
Al Pacino, Scarface, | Say hello to my little friend!
8+
Heath Ledger, The Dark Knight, | Why so serious?
9+
Tom Hanks, Forrest Gump, | Life is like a box of chocolates. You never know what you're gonna get.
10+
Morgan Freeman, The Shawshank Redemption, | Get busy living, or get busy dying.
11+
Vivien Leigh, Gone with the Wind, | After all, tomorrow is another day!
12+
Jack Nicholson, A Few Good Men, | You can't handle the truth!
13+
Robert De Niro, Taxi Driver, | You talkin' to me?
14+
Humphrey Bogart, Casablanca, | Here's looking at you, kid.
15+
Meryl Streep, The Devil Wears Prada, | That's all.
16+
Robin Williams, Dead Poets Society, | Carpe diem. Seize the day, boys. Make your lives extraordinary.
17+
Leonardo DiCaprio, Titanic, | I'm the king of the world!
18+
Tom Cruise, Jerry Maguire, | Show me the money!
19+
Anthony Hopkins, The Silence of the Lambs, | I do wish we could chat longer, but I'm having an old friend for dinner.
20+
Johnny Depp, Pirates of the Caribbean, | This is the day you will always remember as the day you almost caught Captain Jack Sparrow.
21+
Harrison Ford, Star Wars, | May the Force be with you.
22+
Keanu Reeves, The Matrix, | There is no spoon.
23+
Russell Crowe, Gladiator, | Are you not entertained?
24+
Macaulay Culkin, Home Alone, | Keep the change, ya filthy animal.
25+
Sigourney Weaver, Aliens, | Get away from her, you b****!
26+
Julie Andrews, The Sound of Music, | The hills are alive with the sound of music.
27+
Gene Wilder, Willy Wonka & the Chocolate Factory, | We are the music makers, and we are the dreamers of dreams.
28+
Charlton Heston, Planet of the Apes, | Take your stinking paws off me, you damned dirty ape!
29+
Michael J. Fox, Back to the Future, | Roads? Where we're going, we don't need roads.
30+
Audrey Hepburn, Breakfast at Tiffany's, | Nothing very bad could happen to you there.
46 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)