Skip to content

Commit

Permalink
Add initial backend implementation with quote retrieval, weather fore…
Browse files Browse the repository at this point in the history
…cast, and Wikipedia article summary
  • Loading branch information
Wambaforestin committed Dec 9, 2024
1 parent 324c4f9 commit 3d6e148
Show file tree
Hide file tree
Showing 6 changed files with 282 additions and 0 deletions.
121 changes: 121 additions & 0 deletions start_your_day/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
/backend/.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/
131 changes: 131 additions & 0 deletions start_your_day/backend/content.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import csv
import random
import os
from dotenv import load_dotenv
from urllib import request
import json
import datetime

load_dotenv()

"""
Load a random quote from a CSV file and return it as a dictionary.
"""
def get_random_quote(quotes_file='quotes.csv'):
try: #load the quotes from the csv file
with open(quotes_file, 'r') as file:
quotes = [{'author': line[0], 'quote': line[1]} for line in csv.reader(file, delimiter='|')]
except Exception as e: # if there is an exception, return a default quote
print(f'Error loading quotes: {e}')
quotes = [{'author': 'Unknown', 'quote': 'An error occurred while loading the quotes. Please try again later.'}]

return random.choice(quotes) # return a random quote

"""
Get the weather forecast for a specific location using the OpenWeatherMap API.
"""
def get_weather_forecast(my_coords={'lat': 48.9881, 'lon': 2.2339}):
try:
# Retrieve the weather forecast from the OpenWeatherMap API
api_key = os.getenv('WEATHER_API_KEY') # Get the API key from environment variables
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'
response = json.load(request.urlopen(url))

# Process the API response into a clean structure
forecast = {
"city": response['city']['name'],
"country": response['city']['country'],
"forecast": [] # List to store the forecast for the next periods
}

for period in response['list'][:9]: # Get the first 9 forecast periods
forecast['forecast'].append({
'timestamp': datetime.datetime.fromtimestamp(period['dt']).strftime('%Y-%m-%d %H:%M:%S'),
'temperature': period['main']['temp'],
'description': period['weather'][0]['description'].title(),
'icon': f"https://openweathermap.org/img/wn/{period['weather'][0]['icon']}@2x.png"
})

return forecast

except Exception as e:
# Handle errors and return a default structure
print(f'Error loading weather forecast: {e}')
return {
"city": "Unknown",
"country": "Unknown",
"forecast": []
}

"""
Get a random summary of Wikipedia articles.
"""
def get_wikipedia_article():
try:
# Retrieve a random Wikipedia article summary using the Wikipedia API
url = 'https://en.wikipedia.org/api/rest_v1/page/random/summary'
response = json.load(request.urlopen(url))

# Process the API response into a clean structure
article = {
"title": response['title'],
"extract": response['extract'],
"url": response['content_urls']['desktop']['page']
}

return article

except Exception as e:
# Handle errors and return a default structure
print(f'Error loading Wikipedia article: {e}')
return {
"title": "Unknown",
"extract": "An error occurred while loading the Wikipedia article. Please try again later.",
"url": "#"
}


if __name__ == '__main__':
# Test the get_random_quote function
print("Testing the get_random_quote function")
quote = get_random_quote()
print(f"Quote: {quote['quote']}, Author: {quote['author']}")

quote = get_random_quote('quotes2.csv')
print(f"Quote: {quote['quote']} Author: {quote['author']}")

# Test the get_weather_forecast function
print("\nTesting the get_weather_forecast function")

# Test the default location
forecast = get_weather_forecast() # Default location
print(f"City: {forecast['city']}, Country: {forecast['country']}")
for period in forecast['forecast']:
print(f"Timestamp: {period['timestamp']}, Temperature: {period['temperature']}, "
f"Description: {period['description']}, Icon: {period['icon']}")

# Test the get_weather_forecast function with a custom location in Paris
print("\nTesting with a custom location: Paris, France")
forecast = get_weather_forecast({'lat': 48.8566, 'lon': 2.3522}) # Paris, France
print(f"City: {forecast['city']}, Country: {forecast['country']}")
for period in forecast['forecast']:
print(f"Timestamp: {period['timestamp']}, Temperature: {period['temperature']}, "
f"Description: {period['description']}, Icon: {period['icon']}")

# Test the error handling with an invalid location
print("\nTesting with an invalid location: (0, 0)")
forecast = get_weather_forecast({'lat': 0, 'lon': 0}) # Invalid location
print(f"City: {forecast['city']}, Country: {forecast['country']}")
for period in forecast['forecast']:
print(f"Timestamp: {period['timestamp']}, Temperature: {period['temperature']}, "
f"Description: {period['description']}, Icon: {period['icon']}")

# Test the get_wikipedia_article function
print("\nTesting the get_wikipedia_article function")
article = get_wikipedia_article()
print(f"Title: {article['title']}")
print(f"Extract: {article['extract']}")
print(f"URL: {article['url']}")



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

0 comments on commit 3d6e148

Please sign in to comment.