Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE]: Publish monthly a plot on Twitter with the gas price variation #9 #11

Merged
merged 14 commits into from
Jan 11, 2023
23 changes: 23 additions & 0 deletions .github/workflows/history_plot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Publish history plot
on:
schedule:
- cron: "0 0 1 * *"
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checks out the repository
uses: actions/checkout@v2
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Setup Python
uses: actions/setup-python@v3.1.2
- name: Install project requirements
run: pip install -r requirements.txt
- name: Post history plot
env:
CONSUMER_KEY: ${{ secrets.CONSUMER_KEY }}
CONSUMER_SECRET: ${{ secrets.CONSUMER_SECRET }}
ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }}
ACCESS_TOKEN_SECRET: ${{ secrets.ACCESS_TOKEN_SECRET }}
run: python script_post_plot_history.py
1 change: 1 addition & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,6 @@ jobs:
git add gas_info.json
git add history/gas_info_history.csv
git add history/gas_info_history.json
git add history/img/plot.png
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line should be removed since you are not writing the file on the repo any more.

git diff-index --quiet HEAD || git commit -m "Update gas information"
git push
6 changes: 3 additions & 3 deletions add_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
def add_history(dict_prices):
# JSON
with open(CURRENT_GAS_HISTORY_JSON_FILE, 'r') as f:
curret_data = json.load(f)
current_data = json.load(f)
with open(CURRENT_GAS_HISTORY_JSON_FILE, 'w') as f:
curret_data[dict_prices[CURRENT_WEEK][START_DATE_KEY]] = dict_prices[CURRENT_WEEK]
content = json.dumps(curret_data, indent=1, ensure_ascii=False)
current_data[dict_prices[CURRENT_WEEK][START_DATE_KEY]] = dict_prices[CURRENT_WEEK]
content = json.dumps(current_data, indent=1, ensure_ascii=False)
f.write(content)
# CSV
with open(CURRENT_GAS_HISTORY_CSV_FILE, 'a') as f:
Expand Down
25 changes: 21 additions & 4 deletions constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,26 @@
GASOLINE_95_TW = 'Gasolina 95 '
GASOLINE_98_TW = 'Gasolina 98 '

#PDF_GAS_PRICE_REGEX = r'(?<=€ )([\d,]+)(?= por litro)'
# PDF_GAS_PRICE_REGEX = r'(?<=€ )([\d,]+)(?= por litro)'
PDF_GAS_PRICE_REGEX = r'(%s|%s|%s)(?:[\.€\w ]+)(\d{1},\d{3})' % (
'Gasolina super sem chumbo IO 95',
'Gasóleo rodoviário',
'Gasóleo colorido e marcado'
'Gasolina super sem chumbo IO 95',
'Gasóleo rodoviário',
'Gasóleo colorido e marcado'
)

# History plot
HISTORY_PLOT_LABEL_GASOLINA_IO95 = 'Gasolina IO95'
HISTORY_PLOT_LABEL_GASOLINA_IO98 = 'Gasolina IO98'
HISTORY_PLOT_LABEL_GASOLEO_RODOVIARIO = 'Gasoleo Rodoviario'
HISTORY_PLOT_Y_LABEL = 'Preço (€)'
HISTORY_PLOT_X_LABEL = 'Data'

# CSV columns
COLUMN_START_DATE = 'start_date'
COLUMN_END_DATE = 'end_date'
COLUMN_GASOLINA_IO95 = 'gasolina_IO95'
COLUMN_GASOLINA_IO98 = 'gasolina_IO98'
COLUMN_GASOLEO_RODOVIARIO = 'gasoleo_rodoviario'

# Tweets
TWEET_HISTORY = 'Variação dos preços dos combustíveis na Madeira, de {start_date} a {end_date}.'
23 changes: 23 additions & 0 deletions post_tweet.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,29 @@ def gas_prices_message(price_current, price_previous):
return f'{price_current}€ = {price_previous}€'


def create_api(client):
auth = tweepy.OAuthHandler(
client.consumer_key,
client.consumer_secret,
)
auth.set_access_token(
client.access_token,
client.access_token_secret,
)
return tweepy.API(auth)


def post_image(tweet, image_path):
# Get Twitter client
client = create_client_twitter()
# Create Twitter API
api = create_api(client)
# Upload image
image = api.media_upload(image_path)
# Post tweet
return api.update_status(status=tweet, media_ids=[image.media_id])


def make_tweet(dict_prices):
# Get Twitter client
client = create_client_twitter()
Expand Down
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
requests~=2.27.1
beautifulsoup4~=4.10.0
tweepy~=4.8.0
PyPDF2~=2.9.0
PyPDF2~=2.9.0
matplotlib~=3.5.3
pandas~=1.4.3
5 changes: 2 additions & 3 deletions script.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
i = 1
while i < len(gas_info):
if gas_info[i].startswith(NEW_DATE_KEY):
date_positions.append(i+1)
date_positions.append(i + 1)
i += 1

# Parse the last available date
Expand All @@ -49,8 +49,7 @@
# If we don't have the date, update
if update:
# Prepare the dictionaire
dict_prices = {PREVIOUS_WEEK: curret_data[CURRENT_WEEK]}
dict_prices[CURRENT_WEEK] = {START_DATE_KEY: start_date, END_DATE_KEY: end_date, GAS_KEY: {}}
dict_prices = {PREVIOUS_WEEK: curret_data[CURRENT_WEEK], CURRENT_WEEK: {START_DATE_KEY: start_date, END_DATE_KEY: end_date, GAS_KEY: {}}}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is typo curret_data, should be current_data; this stems from here:

devo-abastecer/script.py

Lines 13 to 15 in 010431a

curret_data = json.load(f)
current_start_date_saved = curret_data[CURRENT_WEEK][START_DATE_KEY]
current_end_date_saved = curret_data[CURRENT_WEEK][END_DATE_KEY]

# Parse the data
i += 1
while i < len(gas_info) - 1:
Expand Down
43 changes: 43 additions & 0 deletions script_post_plot_history.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import locale
import tempfile

import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import pandas as pd

from constants import TWEET_HISTORY, CURRENT_GAS_HISTORY_CSV_FILE, COLUMN_START_DATE, COLUMN_GASOLINA_IO95, COLUMN_GASOLINA_IO98, COLUMN_GASOLEO_RODOVIARIO, HISTORY_PLOT_LABEL_GASOLINA_IO95, HISTORY_PLOT_LABEL_GASOLINA_IO98, HISTORY_PLOT_LABEL_GASOLEO_RODOVIARIO, HISTORY_PLOT_Y_LABEL, HISTORY_PLOT_X_LABEL
from post_tweet import post_image

locale.setlocale(locale.LC_ALL, 'pt_PT.UTF-8')


def generate_plot_history(plot_path):
# Select the last 6 months of data
history = pd.read_csv(CURRENT_GAS_HISTORY_CSV_FILE)
history[COLUMN_START_DATE] = pd.to_datetime(history[COLUMN_START_DATE])
history.set_index(COLUMN_START_DATE, inplace=True)
history = history.last('6M').copy()

# Get start and end dates
start_date, end_date = history.index.min(), history.index.max()

# Generate plot
plt.figure()
plot = history.plot(y=[COLUMN_GASOLINA_IO95, COLUMN_GASOLINA_IO98, COLUMN_GASOLEO_RODOVIARIO],
label=[HISTORY_PLOT_LABEL_GASOLINA_IO95, HISTORY_PLOT_LABEL_GASOLINA_IO98, HISTORY_PLOT_LABEL_GASOLEO_RODOVIARIO], ylabel=HISTORY_PLOT_Y_LABEL, xlabel=HISTORY_PLOT_X_LABEL)

plot.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.3f'))

# Save plot
plt.savefig(plot_path, dpi=300, bbox_inches='tight')

return start_date, end_date, plot


# Generate history plot
temp_dir = tempfile.TemporaryDirectory()
plot_path = temp_dir.name + '/plot.png'
start_date, end_date, plot = generate_plot_history(plot_path)

# Post tweet with image
post_image(TWEET_HISTORY.format(start_date=start_date, end_date=end_date), plot_path)