Modify and produce the complete script such that files to be downloaded and processed up to 202408 (YYYYMM) have the current format (PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_YYYYMM010000.zip).
Files to be downloaded from and including 202408 have the following format: PUBLIC_ARCHIVE#P5MIN_INTERCONNECTORSOLN#FILE01#YYYYMM010000.zip and the corresponding CSV file is in the format:
PUBLIC_ARCHIVE#P5MIN_INTERCONNECTORSOLN#FILE01#YYYYMM010000.CSV
There have been two changes that need to be adjusted in the code:
There are now 4 additional fields in the database table: local_price_adjustment_export, locally_constrained_export, local_price_adjustment_import, locally_constrained_import
The order of the fields in the csv file have changed. Here is the csv field order for files from and including 202408:
I,P5MIN,INTERCONNECTORSOLN,4,RUN_DATETIME,INTERCONNECTORID,INTERVAL_DATETIME,METEREDMWFLOW,MWFLOW,MWLOSSES,MARGINALVALUE,VIOLATIONDEGREE,MNSP,EXPORTLIMIT,IMPORTLIMIT,MARGINALLOSS,EXPORTGENCONID,IMPORTGENCONID,FCASEXPORTLIMIT,FCASIMPORTLIMIT,LASTCHANGED,LOCAL_PRICE_ADJUSTMENT_EXPORT,LOCALLY_CONSTRAINED_EXPORT,LOCAL_PRICE_ADJUSTMENT_IMPORT,LOCALLY_CONSTRAINED_IMPORT,INTERVENTION
As previously the first four fields are ignored. The "INTERVENTION" field is now the last field, but its location in the database has not changed.
These fields also need to be imported from the csv file: LOCAL_PRICE_ADJUSTMENT_EXPORT,LOCALLY_CONSTRAINED_EXPORT,LOCAL_PRICE_ADJUSTMENT_IMPORT,LOCALLY_CONSTRAINED_IMPORT
Produce the whole new script
#!/usr/bin/env python3
File name structure: PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_YYYYMM010000.zip
following error:
File "/home/craigfryer/aemo/dl_interconnect_5m_archive_1.1.0.py", line 96
)
^
SyntaxError: positional argument follows keyword argument
Assistant
User
File "/home/craigfryer/aemo/dl_interconnect_5m_archive_1.1.0.py", line 100, in
before_sleep=before_sleep_log(logger, logging.WARNING, message="Retrying {attempt_number} in {sleep_time:.1f} seconds after exception {outcome.exception()}."),
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: before_sleep_log() got an unexpected keyword argument 'message'
start_year, start_month = int(start_year_month[:4]), int(start_year_month[4:])
end_year, end_month = int(end_year_month[:4]), int(end_year_month[4:])
for year in range(start_year, end_year + 1):
# Determine the month range for the given year
if year == start_year and year == end_year:
months = range(start_month, end_month + 1)
elif year == start_year:
months = range(start_month, 13)
elif year == end_year:
months = range(1, end_month + 1)
else:
months = range(1, 13)
for month in months:
month_str = f"{month:02d}"
url = f"{URL_BASE}{year}/MMSDM_{year}_{month_str}/MMSDM_Historical_Data_SQLLoader/DATA/"
# PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_YYYYMM010000.zip
raw_filename = f"PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_{year}{month_str}010000.zip"
encoded_filename = raw_filename.replace("#", "%23")
zip_path = DATA_DIR / raw_filename
# Skip if file already exists
if zip_path.exists():
print_and_log(f"{zip_path} already exists. Skipping download.")
else:
try:
zip_path = download_file(url, DATA_DIR, raw_filename, encoded_filename)
except RetryError as e:
print_and_log(f"Failed to download {url + encoded_filename} after 3 attempts: {e}", e)
continue
if zip_path:
csv_path = unzip_file(zip_path, DATA_DIR)
if csv_path:
process_csv(csv_path)
zip_path.unlink(missing_ok=True)
csv_path.unlink(missing_ok=True)
if name == "main":
parser = argparse.ArgumentParser(description="Download and process AEMO rooftop PV data.")
parser.add_argument("start_year_month", type=str, help="Start year and month in YYYYMM format")
parser.add_argument("end_year_month", type=str, help="End year and month in YYYYMM format")
Okay, here is the complete script modified to handle the two different file formats and CSV structures based on the date, and to include the four new fields in the database insertion.
I've added comments to highlight the changes made for the new format handling and column mapping.
python
#!/usr/bin/env python3
# File name structure (old): PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_YYYYMM010000.zip
# File name structure (new, from 202408): PUBLIC_ARCHIVE#P5MIN_INTERCONNECTORSOLN#FILE01#YYYYMM010000.zip
# URL structure: https://nemweb.com.au/Data_Archive/Wholesale_Electricity/MMSDM/YYYY/MMSDM_YYYY_MM/MMSDM_Historical_Data_SQLLoader/DATA/
import os
import sys
from pathlib import Path
import requests
import zipfile
import csv
import psycopg2
from psycopg2 import sql, OperationalError
import configparser
from datetime import datetime
from tenacity import retry, stop_after_attempt, wait_fixed, before_sleep_log, retry_if_exception_type, RetryError
import logging
import argparse
# --- Global Constants ---
PROGRAM_VER = "dl_interconnect_5m_archive_1.1.0" # Updated version
URL_BASE = "https://nemweb.com.au/Data_Archive/Wholesale_Electricity/MMSDM/"
# --- Paths ---
CWD = Path(__file__).resolve().parent
DATA_DIR = CWD / "temp"
LOG_DIR = CWD / "log"
LOGFILE = LOG_DIR / "dl_interconnect_5m_archive.log"
HEADERS = {
"User-Agent": "Mozilla/5.0",
"Accept-Encoding": "gzip, deflate"
}
# --- Utilities ---
def ensure_dir_exists(path: Path):
path.mkdir(parents=True, exist_ok=True)
ensure_dir_exists(DATA_DIR)
ensure_dir_exists(LOG_DIR)
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', filename=LOGFILE)
# Add a handler to also print to console
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
# Prevent adding multiple handlers if script is run multiple times
if not logging.getLogger().handlers:
logging.getLogger().addHandler(console_handler)
logger = logging.getLogger(__name__)
def print_and_log(text: str, level=logging.INFO, err: Exception = None):
"""Logs and prints a message."""
if err:
logger.log(level, f"{text} Error: {err}", exc_info=True)
else:
logger.log(level, text)
def print_psycopg2_exception(err: Exception):
"""Logs and prints psycopg2 exceptions with detail."""
_, _, tb = sys.exc_info()
line_num = tb.tb_lineno
msg = f"psycopg2 ERROR: {err} on line {line_num}\npgerror: {err.pgerror}\npgcode: {err.pgcode}"
print_and_log(msg, level=logging.ERROR, err=err)
def config(filename: str = 'aemo_config.ini', section: str = 'postgresql') -> dict:
"""Reads database configuration from a file."""
parser = configparser.ConfigParser()
if not parser.read(filename):
raise FileNotFoundError(f"Configuration file '{filename}' not found.")
if parser.has_section(section):
return dict(parser.items(section))
raise ValueError(f"Section '{section}' not found in '{filename}'")
def connect_db() -> psycopg2.extensions.connection | None:
"""Establishes a database connection."""
try:
params = config()
return psycopg2.connect(**params)
except (OperationalError, FileNotFoundError, ValueError) as err:
print_and_log("Database connection failed.", level=logging.ERROR, err=err)
if isinstance(err, OperationalError):
print_psycopg2_exception(err)
return None
@retry(
stop=stop_after_attempt(3),
wait=wait_fixed(5), # Increased wait time slightly
before_sleep=before_sleep_log(logger, logging.WARNING),
retry=retry_if_exception_type(requests.RequestException)
)
def download_file(url: str, dest_path: Path, filename: str, encoded_filename: str) -> Path | None:
"""Downloads a file with retries."""
full_url = url + encoded_filename
try:
print_and_log(f"Attempting to download: {full_url}")
response = requests.get(full_url, timeout=30, headers=HEADERS) # Increased timeout
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
file_path = dest_path / filename
file_path.write_bytes(response.content)
print_and_log(f"Successfully downloaded: {filename}")
return file_path
except requests.RequestException as e:
print_and_log(f"Error downloading {full_url}: {e}", level=logging.WARNING, err=e)
raise # Re-raise exception to trigger retry
def unzip_file(zip_path: Path, extract_to: Path) -> Path | None:
"""Unzips a file and returns the path to the expected CSV."""
try:
with zipfile.ZipFile(zip_path, 'r') as z:
# Find the expected CSV file name within the zip
expected_csv_name = zip_path.stem + ".CSV"
csv_info = None
for member in z.infolist():
# Case-insensitive match and handle potential directory structures within zip
if Path(member.filename).name.upper() == expected_csv_name.upper():
csv_info = member
break
if not csv_info:
print_and_log(f"Error: Expected CSV file '{expected_csv_name}' not found in zip {zip_path}", level=logging.ERROR)
return None
# Extract the specific CSV file
z.extract(csv_info, extract_to)
csv_path = extract_to / Path(csv_info.filename).name # Use .name to get just the filename
print_and_log(f"Unzipped: {csv_path.name}")
return csv_path
except zipfile.BadZipFile as e:
print_and_log(f"Error unzipping {zip_path}: {e}", level=logging.ERROR, err=e)
except Exception as e:
print_and_log(f"An unexpected error occurred during unzipping {zip_path}: {e}", level=logging.ERROR, err=e)
return None
def process_csv(csv_path: Path, year_month: int):
"""Processes a CSV file and inserts data into the database."""
conn = connect_db()
if not conn:
print_and_log("Database connection failed, exiting process_csv", level=logging.ERROR)
return
# Define column indices based on year_month
# These map the database column names to their *position* in the CSV row[] list
# The first 4 fields ('I', 'P5MIN', etc.) are skipped, so index 0 in the list is the 5th field in the CSV.
# We need to map the *database* column names to the correct CSV index.
# Let's create a mapping from database column name to CSV list index (which is 0-based)
# List of database columns in the order they will appear in the INSERT statement
db_columns = [
'run_datetime', 'intervention', 'interconnectorid', 'interval_datetime',
'meteredmwflow', 'mwflow', 'mwlosses', 'marginalvalue', 'violationdegree',
'mnsp', 'exportlimit', 'importlimit', 'marginalloss', 'exportgenconid',
'importgenconid', 'fcasexportlimit', 'fcasimportlimit', 'lastchanged',
'local_price_adjustment_export', 'locally_constrained_export',
'local_price_adjustment_import', 'locally_constrained_import'
]
# Mapping from database column name to its index in the *CSV data row* (after skipping first 4 fields)
csv_col_indices = {}
min_row_length = 0 # Minimum expected length of a 'D' row
if year_month >= 202408:
# New format (from 202408 onwards)
# CSV columns (after skipping first 4: I,P5MIN,INTERCONNECTORSOLN,4)
# 0:RUN_DATETIME, 1:INTERCONNECTORID, 2:INTERVAL_DATETIME, 3:METEREDMWFLOW, 4:MWFLOW, 5:MWLOSSES,
# 6:MARGINALVALUE, 7:VIOLATIONDEGREE, 8:MNSP, 9:EXPORTLIMIT, 10:IMPORTLIMIT, 11:MARGINALLOSS,
# 12:EXPORTGENCONID, 13:IMPORTGENCONID, 14:FCASEXPORTLIMIT, 15:FCASIMPORTLIMIT, 16:LASTCHANGED,
# 17:LOCAL_PRICE_ADJUSTMENT_EXPORT, 18:LOCALLY_CONSTRAINED_EXPORT, 19:LOCAL_PRICE_ADJUSTMENT_IMPORT,
# 20:LOCALLY_CONSTRAINED_IMPORT, 21:INTERVENTION
csv_col_indices = {
'run_datetime': 0,
'interconnectorid': 1,
'interval_datetime': 2,
'meteredmwflow': 3,
'mwflow': 4,
'mwlosses': 5,
'marginalvalue': 6,
'violationdegree': 7,
'mnsp': 8,
'exportlimit': 9,
'importlimit': 10,
'marginalloss': 11,
'exportgenconid': 12,
'importgenconid': 13,
'fcasexportlimit': 14,
'fcasimportlimit': 15,
'lastchanged': 16,
'local_price_adjustment_export': 17,
'locally_constrained_export': 18,
'local_price_adjustment_import': 19,
'locally_constrained_import': 20,
'intervention': 21 # Intervention moved to the end in CSV
}
min_row_length = 26 # I, P5MIN, INTERCONNECTOR, 4, ... 22 data fields = 26 total columns
else:
# Old format (up to 202407)
# CSV columns (after skipping first 4: I,P5MIN,INTERCONNECTORSOLN,4)
# 0:RUN_DATETIME, 1:INTERVENTION, 2:INTERCONNECTORID, 3:INTERVAL_DATETIME, 4:METEREDMWFLOW,
# 5:MWFLOW, 6:MWLOSSES, 7:MARGINALVALUE, 8:VIOLATIONDEGREE, 9:MNSP, 10:EXPORTLIMIT,
# 11:IMPORTLIMIT, 12:MARGINALLOSS, 13:EXPORTGENCONID, 14:IMPORTGENCONID,
# 15:FCASEXPORTLIMIT, 16:FCASIMPORTLIMIT, 17:LASTCHANGED
csv_col_indices = {
'run_datetime': 0,
'intervention': 1,
'interconnectorid': 2,
'interval_datetime': 3,
'meteredmwflow': 4,
'mwflow': 5,
'mwlosses': 6,
'marginalvalue': 7,
'violationdegree': 8,
'mnsp': 9,
'exportlimit': 10,
'importlimit': 11,
'marginalloss': 12,
'exportgenconid': 13,
'importgenconid': 14,
'fcasexportlimit': 15,
'fcasimportlimit': 16,
'lastchanged': 17,
# New fields are NULL in old format
'local_price_adjustment_export': None,
'locally_constrained_export': None,
'local_price_adjustment_import': None,
'locally_constrained_import': None
}
min_row_length = 22 # I, P5MIN, INTERCONNECTOR, 4, ... 18 data fields = 22 total columns
try:
with conn.cursor() as cur:
# Use copy_expert for potentially faster inserts, though executemany is also fine.
# Let's stick with executemany for clarity and easier debugging of individual rows if needed,
# especially with the mixed old/new format logic.
with open(csv_path, 'r') as file:
csv_reader = csv.reader(file)
header = next(csv_reader) # Skip header row
# Optional: Check header to confirm file type if needed, but filename is primary indicator
print_and_log(f"Processing CSV file: {csv_path.name}")
rows_to_insert = []
row_count = 0
for row in csv_reader:
row_count += 1
# Skip comment lines (starting with C or R) or empty lines
if not row or row[0] != "D":
continue
# Check minimum expected row length
if len(row) < min_row_length:
print_and_log(f"Skipping short row {row_count} ({len(row)} < {min_row_length}): {row}", level=logging.WARNING)
continue
# Extract data using the defined indices
try:
# Extract mandatory fields first (used for ON CONFLICT)
interconnectorid = row[csv_col_indices['interconnectorid'] + 4].strip()
interval_datetime_str = row[csv_col_indices['interval_datetime'] + 4].strip().strip('"')
interval_datetime = datetime.strptime(interval_datetime_str, "%Y/%m/%d %H:%M:%S") if interval_datetime_str else None
# Basic validation for mandatory fields
if not interconnectorid or not interval_datetime:
print_and_log(f"Skipping row {row_count} due to missing key data (InterconnectorID or IntervalDatetime): {row}", level=logging.WARNING)
continue
# Extract other fields based on format
run_datetime_str = row[csv_col_indices['run_datetime'] + 4].strip().strip('"')
run_datetime = datetime.strptime(run_datetime_str, "%Y/%m/%d %H:%M:%S") if run_datetime_str else None
lastchanged_str = row[csv_col_indices['lastchanged'] + 4].strip().strip('"')
lastchanged = datetime.strptime(lastchanged_str, "%Y/%m/%d %H:%M:%S") if lastchanged_str else None
# Helper to safely get float, int, or string, returning None on error/empty
def safe_float(r, index):
if index is not None and r[index + 4].strip():
try: return float(r[index + 4].strip())
except ValueError: return None
return None
def safe_int(r, index):
if index is not None and r[index + 4].strip():
try: return int(r[index + 4].strip())
except ValueError: return None
return None
def safe_str(r, index):
if index is not None and r[index + 4].strip():
return r[index + 4].strip()
return None
# Collect all fields in the order of db_columns list
values = (
run_datetime,
safe_int(row, csv_col_indices['intervention']),
interconnectorid,
interval_datetime,
safe_float(row, csv_col_indices['meteredmwflow']),
safe_float(row, csv_col_indices['mwflow']),
safe_float(row, csv_col_indices['mwlosses']),
safe_float(row, csv_col_indices['marginalvalue']),
safe_float(row, csv_col_indices['violationdegree']),
safe_int(row, csv_col_indices['mnsp']),
safe_float(row, csv_col_indices['exportlimit']),
safe_float(row, csv_col_indices['importlimit']),
safe_float(row, csv_col_indices['marginalloss']),
safe_str(row, csv_col_indices['exportgenconid']),
safe_str(row, csv_col_indices['importgenconid']),
safe_float(row, csv_col_indices['fcasexportlimit']),
safe_float(row, csv_col_indices['fcasimportlimit']),
lastchanged,
# New fields - will be None if index was None (old format)
safe_float(row, csv_col_indices['local_price_adjustment_export']),
safe_float(row, csv_col_indices['locally_constrained_export']),
safe_float(row, csv_col_indices['local_price_adjustment_import']),
safe_float(row, csv_col_indices['locally_constrained_import'])
)
rows_to_insert.append(values)
except Exception as e:
print_and_log(f"Error parsing row {row_count}: {row}. Error: {e}", level=logging.ERROR, err=e)
continue # Skip this row and continue with the next
print_and_log(f"Parsed {len(rows_to_insert)} potentially valid rows from {csv_path.name}")
if rows_to_insert:
try:
# Construct the INSERT statement with all columns
insert_sql = sql.SQL("""
INSERT INTO nem_interconnect_5m ({})
VALUES ({})
ON CONFLICT (interconnectorid, interval_datetime) DO NOTHING
""").format(
sql.SQL(', ').join(map(sql.Identifier, db_columns)),
sql.SQL(', ').join(sql.Placeholder() * len(db_columns))
)
cur.executemany(insert_sql, rows_to_insert)
conn.commit()
print_and_log(f"{cur.rowcount} records inserted/updated from {csv_path.name}")
except Exception as e:
conn.rollback()
print_and_log(f"Error during executemany insert for {csv_path}: {e}", level=logging.ERROR, err=e)
# Optional: Log problematic rows individually for detailed debugging
# print_and_log("Attempting individual inserts for detailed error logging (may be slow)...", level=logging.WARNING)
# for i, row_data in enumerate(rows_to_insert):
# try:
# cur.execute(insert_sql, row_data)
# # print_and_log(f"Successfully inserted row {i+1}", level=logging.DEBUG)
# except Exception as insert_err:
# print_and_log(f"Detailed insert error on row {i+1}: {row_data}. Error: {insert_err}", level=logging.ERROR, err=insert_err)
# conn.commit() # Commit any successful individual inserts
except FileNotFoundError:
print_and_log(f"CSV file not found: {csv_path}", level=logging.ERROR)
except Exception as e:
conn.rollback()
print_and_log(f"Outer error processing {csv_path}: {e}", level=logging.ERROR, err=e)
finally:
if conn:
conn.close()
print_and_log("Database connection closed.")
# --- Main Execution ---
def main(start_year_month: str, end_year_month: str):
print_and_log(f"Program version: {PROGRAM_VER}")
try:
start_year_month_int = int(start_year_month)
end_year_month_int = int(end_year_month)
start_year, start_month = start_year_month_int // 100, start_year_month_int % 100
end_year, end_month = end_year_month_int // 100, end_year_month_int % 100
except ValueError:
print_and_log("Invalid year-month format. Please use YYYYMM.", level=logging.ERROR)
sys.exit(1)
if start_year_month_int > end_year_month_int:
print_and_log("Start year-month cannot be after end year-month.", level=logging.ERROR)
sys.exit(1)
for year in range(start_year, end_year + 1):
# Determine the month range for the given year
if year == start_year and year == end_year:
months = range(start_month, end_month + 1)
elif year == start_year:
months = range(start_month, 13)
elif year == end_year:
months = range(1, end_month + 1)
else:
months = range(1, 13)
for month in months:
month_str = f"{month:02d}"
year_month_int = year * 100 + month # Calculate YYYYMM integer
# Construct URL (remains consistent)
url = f"{URL_BASE}{year}/MMSDM_{year}_{month_str}/MMSDM_Historical_Data_SQLLoader/DATA/"
# Determine filename based on date
if year_month_int >= 202408:
# New format
raw_filename = f"PUBLIC_ARCHIVE#P5MIN_INTERCONNECTORSOLN#FILE01#{year}{month_str}010000.zip"
else:
# Old format
raw_filename = f"PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_{year}{month_str}010000.zip"
# Encode '#' for the URL
encoded_filename = raw_filename.replace("#", "%23")
zip_path = DATA_DIR / raw_filename # Local path uses the raw filename
# Skip if file already exists locally
if zip_path.exists():
print_and_log(f"{zip_path} already exists. Skipping download.")
else:
try:
# download_file returns the zip_path on success
zip_path = download_file(url, DATA_DIR, raw_filename, encoded_filename)
except RetryError as e:
print_and_log(f"Failed to download {url + encoded_filename} after multiple attempts. Skipping processing for this month.", level=logging.ERROR, err=e)
continue # Skip to the next month/file
# Process the file if download or local existence was successful
if zip_path and zip_path.exists(): # Ensure zip_path exists after download attempt or check
# Pass the year_month integer to process_csv
csv_path = unzip_file(zip_path, DATA_DIR)
if csv_path:
process_csv(csv_path, year_month_int)
# Clean up files
zip_path.unlink(missing_ok=True)
csv_path.unlink(missing_ok=True)
print_and_log(f"Cleaned up {zip_path.name} and {csv_path.name}")
elif zip_path.exists():
# If unzip failed but zip exists, maybe keep zip for inspection, or delete?
# Decide based on desired behavior. For now, keep zip if unzip fails.
print_and_log(f"Unzipping failed for {zip_path}. Keeping zip file for inspection.", level=logging.WARNING)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Download and process AEMO P5MIN Interconnector data.")
parser.add_argument("start_year_month", type=str, help="Start year and month in YYYYMM format (e.g., 202301)")
parser.add_argument("end_year_month", type=str, help="End year and month in YYYYMM format (e.g., 202408)")
args = parser.parse_args()
main(args.start_year_month, args.end_year_month)
Summary of Changes:
Version Update:PROGRAM_VER incremented.
Logging: Switched to Python's built-in logging module for better control over output levels and destinations (file and console).
process_csv Refactoring:
The function now accepts year_month (as an integer YYYYMM) as an argument.
Logic is added at the beginning to define csv_col_indices mapping based on year_month. This dictionary stores the 0-based index within the data part of the CSV row (after skipping the first 4 fields) for each required database column. For the new fields in the old format, the index is set to None.
min_row_length is set based on the format to check if a row is too short.
The parsing loop now uses the csv_col_indices dictionary to access the correct data from the row list, adding 4 to the index because the first 4 CSV fields are skipped.
Helper functions (safe_float, safe_int, safe_str) are introduced to simplify extracting and converting data, handling empty strings and None indices gracefully.
The rows_to_insert tuple is constructed with all database columns, ensuring the new fields (local_price_adjustment_export, etc.) are included. For old formats, the safe_* helpers will return None for these fields.
The INSERT statement is dynamically built using psycopg2.sql to include all 22 database columns.
Error logging within the parsing loop is improved.
main Loop Refactoring:
The year_month_int is calculated inside the loop.
An if year_month_int >= 202408: block now determines the raw_filename format (PUBLIC_ARCHIVE#... vs PUBLIC_DVD_...).
The # in the new filename is explicitly handled for URL encoding (encoded_filename) but the local zip_path uses the raw_filename.
The year_month_int is passed to process_csv.
Added basic validation for start/end dates.
unzip_file Improvement: Added logic to specifically look for the expected CSV file name () within the zip archive, making it more robust than assuming the first file is the one needed. It also handles potential subdirectories within the zip.
Remember to create the necessary columns in your nem_interconnect_5m PostgreSQL table before running this script for dates from 202408 onwards. The DDL for the new columns would look something like:
(Using NUMERIC or DECIMAL is generally preferred over FLOAT for financial/price data in databases).
You are absolutely correct. The error SyntaxError: positional argument follows keyword argument on line 96 (and likely the corresponding line in the other @retry decorator) is due to the before_sleep_log function in tenacity.
It expects the message string as a keyword argument message, not a positional argument after the logger and level.
The fix is to add message="..." to the before_sleep_log calls.
Here is the corrected script:
python
#!/usr/bin/env python3
# File name structure (old): PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_YYYYMM010000.zip
# File name structure (new, from 202408): PUBLIC_ARCHIVE#P5MIN_INTERCONNECTORSOLN#FILE01#YYYYMM010000.zip
# URL structure: https://nemweb.com.au/Data_Archive/Wholesale_Electricity/MMSDM/YYYY/MMSDM_YYYY_MM/MMSDM_Historical_Data_SQLLoader/DATA/
import os
import sys
from pathlib import Path
import requests
import zipfile
import csv
import psycopg2
from psycopg2 import sql, OperationalError
import configparser
from datetime import datetime
from tenacity import retry, stop_after_attempt, wait_fixed, before_sleep_log, retry_if_exception_type, RetryError
import logging
import argparse
# --- Global Constants ---
PROGRAM_VER = "dl_interconnect_5m_archive_1.1.1" # Updated version to reflect bug fix
URL_BASE = "https://nemweb.com.au/Data_Archive/Wholesale_Electricity/MMSDM/"
# --- Paths ---
CWD = Path(__file__).resolve().parent
DATA_DIR = CWD / "temp"
LOG_DIR = CWD / "log"
LOGFILE = LOG_DIR / "dl_interconnect_5m_archive.log"
HEADERS = {
"User-Agent": "Mozilla/5.0",
"Accept-Encoding": "gzip, deflate"
}
# --- Utilities ---
def ensure_dir_exists(path: Path):
path.mkdir(parents=True, exist_ok=True)
ensure_dir_exists(DATA_DIR)
ensure_dir_exists(LOG_DIR)
# Configure logging
# Ensure handlers are only added once if running interactively or in complex scenarios
logger = logging.getLogger(__name__)
if not logger.handlers:
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(LOGFILE)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(console_handler)
def print_and_log(text: str, level=logging.INFO, err: Exception = None):
"""Logs and prints a message."""
if err:
# Use exc_info=True to include traceback in log file for ERRORs
logger.log(level, text, exc_info=(level >= logging.ERROR))
else:
logger.log(level, text)
def print_psycopg2_exception(err: Exception):
"""Logs and prints psycopg2 exceptions with detail."""
_, _, tb = sys.exc_info()
line_num = tb.tb_lineno
msg = f"psycopg2 ERROR: {err} on line {line_num}\npgerror: {err.pgerror}\npgcode: {err.pgcode}"
print_and_log(msg, level=logging.ERROR, err=err)
def config(filename: str = 'aemo_config.ini', section: str = 'postgresql') -> dict:
"""Reads database configuration from a file."""
parser = configparser.ConfigParser()
if not parser.read(filename):
raise FileNotFoundError(f"Configuration file '{filename}' not found.")
if parser.has_section(section):
return dict(parser.items(section))
raise ValueError(f"Section '{section}' not found in '{filename}'")
def connect_db() -> psycopg2.extensions.connection | None:
"""Establishes a database connection."""
try:
params = config()
return psycopg2.connect(**params)
except (OperationalError, FileNotFoundError, ValueError) as err:
print_and_log("Database connection failed.", level=logging.ERROR, err=err)
if isinstance(err, OperationalError):
print_psycopg2_exception(err)
return None
@retry(
stop=stop_after_attempt(3),
wait=wait_fixed(5),
# FIX: Add the 'message' keyword argument
before_sleep=before_sleep_log(logger, logging.WARNING, message="Retrying {attempt_number} in {sleep_time:.1f} seconds after exception {outcome.exception()}."),
retry=retry_if_exception_type(requests.RequestException)
)
def download_file(url: str, dest_path: Path, filename: str, encoded_filename: str) -> Path | None:
"""Downloads a file with retries."""
full_url = url + encoded_filename
try:
print_and_log(f"Attempting to download: {full_url}")
response = requests.get(full_url, timeout=30, headers=HEADERS)
response.raise_for_status()
file_path = dest_path / filename
file_path.write_bytes(response.content)
print_and_log(f"Successfully downloaded: {filename}")
return file_path
except requests.RequestException as e:
print_and_log(f"Error downloading {full_url}: {e}", level=logging.WARNING, err=e)
raise # Re-raise exception to trigger retry
def unzip_file(zip_path: Path, extract_to: Path) -> Path | None:
"""Unzips a file and returns the path to the expected CSV."""
try:
with zipfile.ZipFile(zip_path, 'r') as z:
# Find the expected CSV file name within the zip
expected_csv_name = zip_path.stem + ".CSV"
csv_info = None
for member in z.infolist():
# Case-insensitive match and handle potential directory structures within zip
# Also check if it's a file, not a directory
if not member.is_dir() and Path(member.filename).name.upper() == expected_csv_name.upper():
csv_info = member
break
if not csv_info:
print_and_log(f"Error: Expected CSV file '{expected_csv_name}' not found in zip {zip_path}", level=logging.ERROR)
return None
# Extract the specific CSV file
# Need to ensure the target path for extraction is just the filename in extract_to dir
extracted_path = extract_to / Path(csv_info.filename).name
# Prevent directory traversal attacks just in case (zipSlip) - though standard extract is safer
if not str(extracted_path).startswith(str(extract_to)):
print_and_log(f"ZipSlip potential detected! Skipping extraction of {csv_info.filename}", level=logging.ERROR)
return None
z.extract(csv_info, extract_to)
print_and_log(f"Unzipped: {extracted_path.name}")
return extracted_path
except zipfile.BadZipFile as e:
print_and_log(f"Error unzipping {zip_path}: {e}", level=logging.ERROR, err=e)
except Exception as e:
print_and_log(f"An unexpected error occurred during unzipping {zip_path}: {e}", level=logging.ERROR, err=e)
return None
def process_csv(csv_path: Path, year_month: int):
"""Processes a CSV file and inserts data into the database."""
conn = connect_db()
if not conn:
print_and_log("Database connection failed, exiting process_csv", level=logging.ERROR)
return
# Define column indices based on year_month
# These map the database column names to their *position* in the CSV row[] list
# The first 4 fields ('I', 'P5MIN', etc.) are skipped, so index 0 in the list is the 5th field in the CSV.
# We need to map the *database* column names to the correct CSV index.
# Let's create a mapping from database column name to CSV list index (which is 0-based)
# List of database columns in the order they will appear in the INSERT statement
db_columns = [
'run_datetime', 'intervention', 'interconnectorid', 'interval_datetime',
'meteredmwflow', 'mwflow', 'mwlosses', 'marginalvalue', 'violationdegree',
'mnsp', 'exportlimit', 'importlimit', 'marginalloss', 'exportgenconid',
'importgenconid', 'fcasexportlimit', 'fcasimportlimit', 'lastchanged',
'local_price_adjustment_export', 'locally_constrained_export',
'local_price_adjustment_import', 'locally_constrained_import'
]
# Mapping from database column name to its index in the *CSV data row* (after skipping first 4 fields)
csv_col_indices = {}
min_row_length = 0 # Minimum expected length of a 'D' row
if year_month >= 202408:
# New format (from 202408 onwards)
# CSV columns (after skipping first 4: I,P5MIN,INTERCONNECTORSOLN,4)
# 0:RUN_DATETIME, 1:INTERCONNECTORID, 2:INTERVAL_DATETIME, 3:METEREDMWFLOW, 4:MWFLOW, 5:MWLOSSES,
# 6:MARGINALVALUE, 7:VIOLATIONDEGREE, 8:MNSP, 9:EXPORTLIMIT, 10:IMPORTLIMIT, 11:MARGINALLOSS,
# 12:EXPORTGENCONID, 13:IMPORTGENCONID, 14:FCASEXPORTLIMIT, 15:FCASIMPORTLIMIT, 16:LASTCHANGED,
# 17:LOCAL_PRICE_ADJUSTMENT_EXPORT, 18:LOCALLY_CONSTRAINED_EXPORT, 19:LOCAL_PRICE_ADJUSTMENT_IMPORT,
# 20:LOCALLY_CONSTRAINED_IMPORT, 21:INTERVENTION
csv_col_indices = {
'run_datetime': 0,
'interconnectorid': 1,
'interval_datetime': 2,
'meteredmwflow': 3,
'mwflow': 4,
'mwlosses': 5,
'marginalvalue': 6,
'violationdegree': 7,
'mnsp': 8,
'exportlimit': 9,
'importlimit': 10,
'marginalloss': 11,
'exportgenconid': 12,
'importgenconid': 13,
'fcasexportlimit': 14,
'fcasimportlimit': 15,
'lastchanged': 16,
'local_price_adjustment_export': 17,
'locally_constrained_export': 18,
'local_price_adjustment_import': 19,
'locally_constrained_import': 20,
'intervention': 21 # Intervention moved to the end in CSV
}
min_row_length = 4 + 22 # I, P5MIN, INTERCONNECTOR, 4 + 22 data fields = 26 total columns
else:
# Old format (up to 202407)
# CSV columns (after skipping first 4: I,P5MIN,INTERCONNECTORSOLN,4)
# 0:RUN_DATETIME, 1:INTERVENTION, 2:INTERCONNECTORID, 3:INTERVAL_DATETIME, 4:METEREDMWFLOW,
# 5:MWFLOW, 6:MWLOSSES, 7:MARGINALVALUE, 8:VIOLATIONDEGREE, 9:MNSP, 10:EXPORTLIMIT,
# 11:IMPORTLIMIT, 12:MARGINALLOSS, 13:EXPORTGENCONID, 14:IMPORTGENCONID,
# 15:FCASEXPORTLIMIT, 16:FCASIMPORTLIMIT, 17:LASTCHANGED
csv_col_indices = {
'run_datetime': 0,
'intervention': 1,
'interconnectorid': 2,
'interval_datetime': 3,
'meteredmwflow': 4,
'mwflow': 5,
'mwlosses': 6,
'marginalvalue': 7,
'violationdegree': 8,
'mnsp': 9,
'exportlimit': 10,
'importlimit': 11,
'marginalloss': 12,
'exportgenconid': 13,
'importgenconid': 14,
'fcasexportlimit': 15,
'fcasimportlimit': 16,
'lastchanged': 17,
# New fields are NULL in old format - set index to None
'local_price_adjustment_export': None,
'locally_constrained_export': None,
'local_price_adjustment_import': None,
'locally_constrained_import': None
}
min_row_length = 4 + 18 # I, P5MIN, INTERCONNECTOR, 4 + 18 data fields = 22 total columns
try:
with conn.cursor() as cur:
with open(csv_path, 'r') as file:
csv_reader = csv.reader(file)
header = next(csv_reader) # Skip header row
# Optional: Check header to confirm file type if needed, but filename is primary indicator
print_and_log(f"Processing CSV file: {csv_path.name}")
rows_to_insert = []
row_count = 0
for row in csv_reader:
row_count += 1
# Skip comment lines (starting with C or R) or empty lines
if not row or row[0] != "D":
continue
# Check minimum expected row length - Use len(row) > index + 4
# A more robust check: check if the *last* expected field's index + 4 is within bounds
last_expected_index_plus_4 = max((idx if idx is not None else -5) for idx in csv_col_indices.values()) + 4 # Use -5 if None to handle old format correctly
if len(row) < last_expected_index_plus_4 +1: # +1 because row is 0-indexed, length is 1-indexed
print_and_log(f"Skipping short row {row_count} ({len(row)} < {last_expected_index_plus_4 + 1} expected minimum): {row}", level=logging.WARNING)
continue
# Extract data using the defined indices
try:
# Helper to safely get float, int, string, or datetime, returning None on error/empty
def safe_get_value(r, index, value_type):
if index is None: # Field not present in this file format
return None
csv_index = index + 4 # Adjust for the skipped 4 header fields
if csv_index >= len(r) or not r[csv_index].strip():
return None # Index out of bounds or value is empty
value_str = r[csv_index].strip().strip('"')
if not value_str:
return None
try:
if value_type == 'datetime':
return datetime.strptime(value_str, "%Y/%m/%d %H:%M:%S")
elif value_type == 'float':
return float(value_str)
elif value_type == 'int':
return int(value_str)
elif value_type == 'str':
return value_str
else:
return value_str # Default to string if type unknown
except ValueError:
# Log parsing errors for specific cells
print_and_log(f"Value Error parsing row {row_count}, column index {index}: '{r[csv_index]}'. Expected type {value_type}.", level=logging.WARNING)
return None # Return None if parsing fails
# Collect all fields in the order of db_columns list
values = (
safe_get_value(row, csv_col_indices['run_datetime'], 'datetime'),
safe_get_value(row, csv_col_indices['intervention'], 'int'),
safe_get_value(row, csv_col_indices['interconnectorid'], 'str'), # Should always exist, but use helper for consistency
safe_get_value(row, csv_col_indices['interval_datetime'], 'datetime'), # Should always exist
safe_get_value(row, csv_col_indices['meteredmwflow'], 'float'),
safe_get_value(row, csv_col_indices['mwflow'], 'float'),
safe_get_value(row, csv_col_indices['mwlosses'], 'float'),
safe_get_value(row, csv_col_indices['marginalvalue'], 'float'),
safe_get_value(row, csv_col_indices['violationdegree'], 'float'),
safe_get_value(row, csv_col_indices['mnsp'], 'int'),
safe_get_value(row, csv_col_indices['exportlimit'], 'float'),
safe_get_value(row, csv_col_indices['importlimit'], 'float'),
safe_get_value(row, csv_col_indices['marginalloss'], 'float'),
safe_get_value(row, csv_col_indices['exportgenconid'], 'str'),
safe_get_value(row, csv_col_indices['importgenconid'], 'str'),
safe_get_value(row, csv_col_indices['fcasexportlimit'], 'float'),
safe_get_value(row, csv_col_indices['fcasimportlimit'], 'float'),
safe_get_value(row, csv_col_indices['lastchanged'], 'datetime'),
# New fields - will be None if index was None (old format)
safe_get_value(row, csv_col_indices['local_price_adjustment_export'], 'float'),
safe_get_value(row, csv_col_indices['locally_constrained_export'], 'float'),
safe_get_value(row, csv_col_indices['local_price_adjustment_import'], 'float'),
safe_get_value(row, csv_col_indices['locally_constrained_import'], 'float')
)
# Basic validation for mandatory fields used in ON CONFLICT
if values[2] is None or values[3] is None: # interconnectorid, interval_datetime
print_and_log(f"Skipping row {row_count} due to missing key data (InterconnectorID or IntervalDatetime): {row}", level=logging.WARNING)
continue
rows_to_insert.append(values)
except Exception as e:
print_and_log(f"Unexpected Error processing row {row_count}: {row}. Error: {e}", level=logging.ERROR, err=e)
continue # Skip this row and continue with the next
print_and_log(f"Parsed {len(rows_to_insert)} potentially valid rows from {csv_path.name}")
if rows_to_insert:
try:
# Construct the INSERT statement with all columns
insert_sql = sql.SQL("""
INSERT INTO nem_interconnect_5m ({})
VALUES ({})
ON CONFLICT (interconnectorid, interval_datetime) DO NOTHING
""").format(
sql.SQL(', ').join(map(sql.Identifier, db_columns)),
sql.SQL(', ').join(sql.Placeholder() * len(db_columns))
)
cur.executemany(insert_sql, rows_to_insert)
conn.commit()
print_and_log(f"{cur.rowcount} records inserted/updated from {csv_path.name}")
except Exception as e:
conn.rollback()
print_and_log(f"Error during executemany insert for {csv_path}: {e}", level=logging.ERROR, err=e)
# Optional: Log problematic rows individually for detailed debugging
# print_and_log("Attempting individual inserts for detailed error logging (may be slow)...", level=logging.WARNING)
# for i, row_data in enumerate(rows_to_insert):
# try:
# cur.execute(insert_sql, row_data)
# # print_and_log(f"Successfully inserted row {i+1}", level=logging.DEBUG)
# except Exception as insert_err:
# print_and_log(f"Detailed insert error on row {i+1}: {row_data}. Error: {insert_err}", level=logging.ERROR, err=insert_err)
# conn.commit() # Commit any successful individual inserts
except FileNotFoundError:
print_and_log(f"CSV file not found: {csv_path}", level=logging.ERROR)
except Exception as e:
conn.rollback()
print_and_log(f"Outer error processing {csv_path}: {e}", level=logging.ERROR, err=e)
finally:
if conn:
conn.close()
print_and_log("Database connection closed.")
# --- Main Execution ---
def main(start_year_month: str, end_year_month: str):
print_and_log(f"Program version: {PROGRAM_VER}")
try:
start_year_month_int = int(start_year_month)
end_year_month_int = int(end_year_month)
start_year, start_month = start_year_month_int // 100, start_year_month_int % 100
end_year, end_month = end_year_month_int // 100, end_year_month_int % 100
except ValueError:
print_and_log("Invalid year-month format. Please use YYYYMM.", level=logging.ERROR)
sys.exit(1)
if start_year_month_int > end_year_month_int:
print_and_log("Start year-month cannot be after end year-month.", level=logging.ERROR)
sys.exit(1)
for year in range(start_year, end_year + 1):
# Determine the month range for the given year
if year == start_year and year == end_year:
months = range(start_month, end_month + 1)
elif year == start_year:
months = range(start_month, 13)
elif year == end_year:
months = range(1, end_month + 1)
else:
months = range(1, 13)
for month in months:
month_str = f"{month:02d}"
year_month_int = year * 100 + month # Calculate YYYYMM integer
# Construct URL (remains consistent)
url = f"{URL_BASE}{year}/MMSDM_{year}_{month_str}/MMSDM_Historical_Data_SQLLoader/DATA/"
# Determine filename based on date
if year_month_int >= 202408:
# New format
raw_filename = f"PUBLIC_ARCHIVE#P5MIN_INTERCONNECTORSOLN#FILE01#{year}{month_str}010000.zip"
else:
# Old format
raw_filename = f"PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_{year}{month_str}010000.zip"
# Encode '#' for the URL
encoded_filename = raw_filename.replace("#", "%23")
zip_path = DATA_DIR / raw_filename # Local path uses the raw filename
# Skip if file already exists locally
if zip_path.exists():
print_and_log(f"{zip_path} already exists. Skipping download.")
else:
try:
# download_file returns the zip_path on success
zip_path = download_file(url, DATA_DIR, raw_filename, encoded_filename)
except RetryError as e:
print_and_log(f"Failed to download {url + encoded_filename} after multiple attempts. Skipping processing for this month.", level=logging.ERROR, err=e)
continue # Skip to the next month/file
# Process the file if download or local existence was successful
if zip_path and zip_path.exists(): # Ensure zip_path exists after download attempt or check
# Pass the year_month integer to process_csv
csv_path = unzip_file(zip_path, DATA_DIR)
if csv_path and csv_path.exists(): # Ensure csv_path exists after unzip attempt
process_csv(csv_path, year_month_int)
# Clean up files
csv_path.unlink(missing_ok=True)
zip_path.unlink(missing_ok=True) # Only delete zip if CSV processing was attempted
print_and_log(f"Cleaned up {zip_path.name} and {csv_path.name}")
elif zip_path.exists():
# If unzip failed but zip exists, perhaps keep zip for inspection?
print_and_log(f"Unzipping or finding CSV failed for {zip_path}. Keeping zip file for inspection.", level=logging.WARNING)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Download and process AEMO P5MIN Interconnector data.")
parser.add_argument("start_year_month", type=str, help="Start year and month in YYYYMM format (e.g., 202301)")
parser.add_argument("end_year_month", type=str, help="End year and month in YYYYMM format (e.g., 202408)")
args = parser.parse_args()
main(args.start_year_month, args.end_year_month)
You are absolutely right again! My apologies. I got the usage of tenacity.before_sleep_log slightly wrong. It generates its own message using the logger and level you provide; you don't pass the message string itself as a keyword argument.
The message keyword argument is not part of before_sleep_log. It should just be before_sleep_log(logger, logging.WARNING).
Here is the corrected script:
python
#!/usr/bin/env python3
# File name structure (old): PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_YYYYMM010000.zip
# File name structure (new, from 202408): PUBLIC_ARCHIVE#P5MIN_INTERCONNECTORSOLN#FILE01#YYYYMM010000.zip
# URL structure: https://nemweb.com.au/Data_Archive/Wholesale_Electricity/MMSDM/YYYY/MMSDM_YYYY_MM/MMSDM_Historical_Data_SQLLoader/DATA/
import os
import sys
from pathlib import Path
import requests
import zipfile
import csv
import psycopg2
from psycopg2 import sql, OperationalError
import configparser
from datetime import datetime
from tenacity import retry, stop_after_attempt, wait_fixed, before_sleep_log, retry_if_exception_type, RetryError
import logging
import argparse
# --- Global Constants ---
PROGRAM_VER = "dl_interconnect_5m_archive_1.1.2" # Updated version to reflect bug fix
URL_BASE = "https://nemweb.com.au/Data_Archive/Wholesale_Electricity/MMSDM/"
# --- Paths ---
CWD = Path(__file__).resolve().parent
DATA_DIR = CWD / "temp"
LOG_DIR = CWD / "log"
LOGFILE = LOG_DIR / "dl_interconnect_5m_archive.log"
HEADERS = {
"User-Agent": "Mozilla/5.0",
"Accept-Encoding": "gzip, deflate"
}
# --- Utilities ---
def ensure_dir_exists(path: Path):
path.mkdir(parents=True, exist_ok=True)
ensure_dir_exists(DATA_DIR)
ensure_dir_exists(LOG_DIR)
# Configure logging
# Ensure handlers are only added once if running interactively or in complex scenarios
logger = logging.getLogger(__name__)
if not logger.handlers:
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler(LOGFILE)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(console_handler)
def print_and_log(text: str, level=logging.INFO, err: Exception = None):
"""Logs and prints a message."""
if err:
# Use exc_info=True to include traceback in log file for ERRORs
logger.log(level, text, exc_info=(level >= logging.ERROR))
else:
logger.log(level, text)
def print_psycopg2_exception(err: Exception):
"""Logs and prints psycopg2 exceptions with detail."""
_, _, tb = sys.exc_info()
line_num = tb.tb_lineno
msg = f"psycopg2 ERROR: {err} on line {line_num}\npgerror: {err.pgerror}\npgcode: {err.pgcode}"
print_and_log(msg, level=logging.ERROR, err=err)
def config(filename: str = 'aemo_config.ini', section: str = 'postgresql') -> dict:
"""Reads database configuration from a file."""
parser = configparser.ConfigParser()
if not parser.read(filename):
raise FileNotFoundError(f"Configuration file '{filename}' not found.")
if parser.has_section(section):
return dict(parser.items(section))
raise ValueError(f"Section '{section}' not found in '{filename}'")
def connect_db() -> psycopg2.extensions.connection | None:
"""Establishes a database connection."""
try:
params = config()
return psycopg2.connect(**params)
except (OperationalError, FileNotFoundError, ValueError) as err:
print_and_log("Database connection failed.", level=logging.ERROR, err=err)
if isinstance(err, OperationalError):
print_psycopg2_exception(err)
return None
@retry(
stop=stop_after_attempt(3),
wait=wait_fixed(5),
# FIX: Removed the 'message' keyword argument. tenacity provides the message.
before_sleep=before_sleep_log(logger, logging.WARNING),
retry=retry_if_exception_type(requests.RequestException)
)
def download_file(url: str, dest_path: Path, filename: str, encoded_filename: str) -> Path | None:
"""Downloads a file with retries."""
full_url = url + encoded_filename
try:
print_and_log(f"Attempting to download: {full_url}")
response = requests.get(full_url, timeout=30, headers=HEADERS)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
file_path = dest_path / filename
file_path.write_bytes(response.content)
print_and_log(f"Successfully downloaded: {filename}")
return file_path
except requests.RequestException as e:
print_and_log(f"Error downloading {full_url}: {e}", level=logging.WARNING, err=e)
raise # Re-raise exception to trigger retry
def unzip_file(zip_path: Path, extract_to: Path) -> Path | None:
"""Unzips a file and returns the path to the expected CSV."""
try:
with zipfile.ZipFile(zip_path, 'r') as z:
# Find the expected CSV file name within the zip
expected_csv_name = zip_path.stem + ".CSV"
csv_info = None
for member in z.infolist():
# Case-insensitive match and handle potential directory structures within zip
# Also check if it's a file, not a directory
if not member.is_dir() and Path(member.filename).name.upper() == expected_csv_name.upper():
csv_info = member
break
if not csv_info:
print_and_log(f"Error: Expected CSV file '{expected_csv_name}' not found in zip {zip_path}", level=logging.ERROR)
return None
# Extract the specific CSV file
# Need to ensure the target path for extraction is just the filename in extract_to dir
extracted_path = extract_to / Path(csv_info.filename).name
# Prevent directory traversal attacks just in case (zipSlip) - though standard extract is safer
if not str(extracted_path.resolve()).startswith(str(extract_to.resolve())): # Use resolve() for absolute paths
print_and_log(f"ZipSlip potential detected! Skipping extraction of {csv_info.filename}", level=logging.ERROR)
return None
z.extract(csv_info, extract_to)
print_and_log(f"Unzipped: {extracted_path.name}")
return extracted_path
except zipfile.BadZipFile as e:
print_and_log(f"Error unzipping {zip_path}: {e}", level=logging.ERROR, err=e)
except Exception as e:
print_and_log(f"An unexpected error occurred during unzipping {zip_path}: {e}", level=logging.ERROR, err=e)
return None
def process_csv(csv_path: Path, year_month: int):
"""Processes a CSV file and inserts data into the database."""
conn = connect_db()
if not conn:
print_and_log("Database connection failed, exiting process_csv", level=logging.ERROR)
return
# Define column indices based on year_month
# These map the database column names to their *position* in the CSV row[] list
# The first 4 fields ('I', 'P5MIN', etc.) are skipped, so index 0 in the list is the 5th field in the CSV.
# We need to map the *database* column names to the correct CSV index.
# Let's create a mapping from database column name to CSV list index (which is 0-based)
# List of database columns in the order they will appear in the INSERT statement
db_columns = [
'run_datetime', 'intervention', 'interconnectorid', 'interval_datetime',
'meteredmwflow', 'mwflow', 'mwlosses', 'marginalvalue', 'violationdegree',
'mnsp', 'exportlimit', 'importlimit', 'marginalloss', 'exportgenconid',
'importgenconid', 'fcasexportlimit', 'fcasimportlimit', 'lastchanged',
'local_price_adjustment_export', 'locally_constrained_export',
'local_price_adjustment_import', 'locally_constrained_import'
]
# Mapping from database column name to its index in the *CSV data row* (after skipping first 4 fields)
csv_col_indices = {}
if year_month >= 202408:
# New format (from 202408 onwards)
# CSV columns (after skipping first 4: I,P5MIN,INTERCONNECTORSOLN,4)
# 0:RUN_DATETIME, 1:INTERCONNECTORID, 2:INTERVAL_DATETIME, 3:METEREDMWFLOW, 4:MWFLOW, 5:MWLOSSES,
# 6:MARGINALVALUE, 7:VIOLATIONDEGREE, 8:MNSP, 9:EXPORTLIMIT, 10:IMPORTLIMIT, 11:MARGINALLOSS,
# 12:EXPORTGENCONID, 13:IMPORTGENCONID, 14:FCASEXPORTLIMIT, 15:FCASIMPORTLIMIT, 16:LASTCHANGED,
# 17:LOCAL_PRICE_ADJUSTMENT_EXPORT, 18:LOCALLY_CONSTRAINED_EXPORT, 19:LOCAL_PRICE_ADJUSTMENT_IMPORT,
# 20:LOCALLY_CONSTRAINED_IMPORT, 21:INTERVENTION
csv_col_indices = {
'run_datetime': 0,
'interconnectorid': 1,
'interval_datetime': 2,
'meteredmwflow': 3,
'mwflow': 4,
'mwlosses': 5,
'marginalvalue': 6,
'violationdegree': 7,
'mnsp': 8,
'exportlimit': 9,
'importlimit': 10,
'marginalloss': 11,
'exportgenconid': 12,
'importgenconid': 13,
'fcasexportlimit': 14,
'fcasimportlimit': 15,
'lastchanged': 16,
'local_price_adjustment_export': 17,
'locally_constrained_export': 18,
'local_price_adjustment_import': 19,
'locally_constrained_import': 20,
'intervention': 21 # Intervention moved to the end in CSV
}
# The index for 'intervention' (21) + 4 skipped fields = 25.
# So the row must have at least 26 columns (index 0 to 25).
min_data_fields = 22 # The number of fields after the 4 initial ones
else:
# Old format (up to 202407)
# CSV columns (after skipping first 4: I,P5MIN,INTERCONNECTORSOLN,4)
# 0:RUN_DATETIME, 1:INTERVENTION, 2:INTERCONNECTORID, 3:INTERVAL_DATETIME, 4:METEREDMWFLOW,
# 5:MWFLOW, 6:MWLOSSES, 7:MARGINALVALUE, 8:VIOLATIONDEGREE, 9:MNSP, 10:EXPORTLIMIT,
# 11:IMPORTLIMIT, 12:MARGINALLOSS, 13:EXPORTGENCONID, 14:IMPORTGENCONID,
# 15:FCASEXPORTLIMIT, 16:FCASIMPORTLIMIT, 17:LASTCHANGED
csv_col_indices = {
'run_datetime': 0,
'intervention': 1,
'interconnectorid': 2,
'interval_datetime': 3,
'meteredmwflow': 4,
'mwflow': 5,
'mwlosses': 6,
'marginalvalue': 7,
'violationdegree': 8,
'mnsp': 9,
'exportlimit': 10,
'importlimit': 11,
'marginalloss': 12,
'exportgenconid': 13,
'importgenconid': 14,
'fcasexportlimit': 15,
'fcasimportlimit': 16,
'lastchanged': 17,
# New fields are NULL in old format - set index to None
'local_price_adjustment_export': None,
'locally_constrained_export': None,
'local_price_adjustment_import': None,
'locally_constrained_import': None
}
# The index for 'lastchanged' (17) + 4 skipped fields = 21.
# So the row must have at least 22 columns (index 0 to 21).
min_data_fields = 18 # The number of fields after the 4 initial ones
try:
with conn.cursor() as cur:
with open(csv_path, 'r') as file:
csv_reader = csv.reader(file)
header = next(csv_reader) # Skip header row
# Optional: Check header to confirm file type if needed, but filename is primary indicator
print_and_log(f"Processing CSV file: {csv_path.name}")
rows_to_insert = []
row_count = 0
for row in csv_reader:
row_count += 1
# Skip comment lines (starting with C or R) or empty lines
if not row or row[0] != "D":
continue
# Check minimum expected row length
if len(row) < 4 + min_data_fields:
print_and_log(f"Skipping short row {row_count} ({len(row)} < {4 + min_data_fields} expected): {row}", level=logging.WARNING)
continue
# Extract data using the defined indices
try:
# Helper to safely get float, int, string, or datetime, returning None on error/empty
def safe_get_value(r, index, value_type):
if index is None: # Field not present in this file format
return None
csv_index = index + 4 # Adjust for the skipped 4 header fields
# Basic safety check: ensure index is within bounds BEFORE accessing
if csv_index >= len(r):
print_and_log(f"Index out of bounds for row {row_count}, expected CSV data index {index} (overall index {csv_index}). Row length is {len(r)}.", level=logging.WARNING)
return None
value_str = r[csv_index].strip().strip('"')
if not value_str:
return None
try:
if value_type == 'datetime':
return datetime.strptime(value_str, "%Y/%m/%d %H:%M:%S")
elif value_type == 'float':
return float(value_str)
elif value_type == 'int':
return int(value_str)
elif value_type == 'str':
return value_str
else:
return value_str # Default to string if type unknown
except ValueError:
# Log parsing errors for specific cells
print_and_log(f"Value Error parsing row {row_count}, CSV data index {index} (overall index {csv_index}): '{r[csv_index]}'. Expected type {value_type}.", level=logging.WARNING)
return None # Return None if parsing fails
# Collect all fields in the order of db_columns list
values = (
safe_get_value(row, csv_col_indices['run_datetime'], 'datetime'),
safe_get_value(row, csv_col_indices['intervention'], 'int'),
safe_get_value(row, csv_col_indices['interconnectorid'], 'str'), # Should always exist, but use helper for consistency
safe_get_value(row, csv_col_indices['interval_datetime'], 'datetime'), # Should always exist
safe_get_value(row, csv_col_indices['meteredmwflow'], 'float'),
safe_get_value(row, csv_col_indices['mwflow'], 'float'),
safe_get_value(row, csv_col_indices['mwlosses'], 'float'),
safe_get_value(row, csv_col_indices['marginalvalue'], 'float'),
safe_get_value(row, csv_col_indices['violationdegree'], 'float'),
safe_get_value(row, csv_col_indices['mnsp'], 'int'),
safe_get_value(row, csv_col_indices['exportlimit'], 'float'),
safe_get_value(row, csv_col_indices['importlimit'], 'float'),
safe_get_value(row, csv_col_indices['marginalloss'], 'float'),
safe_get_value(row, csv_col_indices['exportgenconid'], 'str'),
safe_get_value(row, csv_col_indices['importgenconid'], 'str'),
safe_get_value(row, csv_col_indices['fcasexportlimit'], 'float'),
safe_get_value(row, csv_col_indices['fcasimportlimit'], 'float'),
safe_get_value(row, csv_col_indices['lastchanged'], 'datetime'),
# New fields - will be None if index was None (old format)
safe_get_value(row, csv_col_indices['local_price_adjustment_export'], 'float'),
safe_get_value(row, csv_col_indices['locally_constrained_export'], 'float'),
safe_get_value(row, csv_col_indices['local_price_adjustment_import'], 'float'),
safe_get_value(row, csv_col_indices['locally_constrained_import'], 'float')
)
# Basic validation for mandatory fields used in ON CONFLICT
if values[2] is None or values[3] is None: # interconnectorid, interval_datetime (based on db_columns order)
print_and_log(f"Skipping row {row_count} due to missing key data (InterconnectorID or IntervalDatetime derived None): {row}", level=logging.WARNING)
continue
rows_to_insert.append(values)
except Exception as e:
print_and_log(f"Unexpected Error processing row {row_count}: {row}. Error: {e}", level=logging.ERROR, err=e)
continue # Skip this row and continue with the next
print_and_log(f"Parsed {len(rows_to_insert)} potentially valid rows from {csv_path.name}")
if rows_to_insert:
try:
# Construct the INSERT statement with all columns
insert_sql = sql.SQL("""
INSERT INTO nem_interconnect_5m ({})
VALUES ({})
ON CONFLICT (interconnectorid, interval_datetime) DO NOTHING
""").format(
sql.SQL(', ').join(map(sql.Identifier, db_columns)),
sql.SQL(', ').join(sql.Placeholder() * len(db_columns))
)
cur.executemany(insert_sql, rows_to_insert)
conn.commit()
print_and_log(f"{cur.rowcount} records inserted/updated from {csv_path.name}")
except Exception as e:
conn.rollback()
print_and_log(f"Error during executemany insert for {csv_path}: {e}", level=logging.ERROR, err=e)
# Optional: Log problematic rows individually for detailed debugging
# print_and_log("Attempting individual inserts for detailed error logging (may be slow)...", level=logging.WARNING)
# for i, row_data in enumerate(rows_to_insert):
# try:
# cur.execute(insert_sql, row_data)
# # print_and_log(f"Successfully inserted row {i+1}", level=logging.DEBUG)
# except Exception as insert_err:
# print_and_log(f"Detailed insert error on row {i+1}: {row_data}. Error: {insert_err}", level=logging.ERROR, err=insert_err)
# conn.commit() # Commit any successful individual inserts
except FileNotFoundError:
print_and_log(f"CSV file not found: {csv_path}", level=logging.ERROR)
except Exception as e:
conn.rollback()
print_and_log(f"Outer error processing {csv_path}: {e}", level=logging.ERROR, err=e)
finally:
if conn:
conn.close()
print_and_log("Database connection closed.")
# --- Main Execution ---
def main(start_year_month: str, end_year_month: str):
print_and_log(f"Program version: {PROGRAM_VER}")
try:
start_year_month_int = int(start_year_month)
end_year_month_int = int(end_year_month)
start_year, start_month = start_year_month_int // 100, start_year_month_int % 100
end_year, end_month = end_year_month_int // 100, end_year_month_int % 100
except ValueError:
print_and_log("Invalid year-month format. Please use YYYYMM.", level=logging.ERROR)
sys.exit(1)
if start_year_month_int > end_year_month_int:
print_and_log("Start year-month cannot be after end year-month.", level=logging.ERROR)
sys.exit(1)
for year in range(start_year, end_year + 1):
# Determine the month range for the given year
if year == start_year and year == end_year:
months = range(start_month, end_month + 1)
elif year == start_year:
months = range(start_month, 13)
elif year == end_year:
months = range(1, end_month + 1)
else:
months = range(1, 13)
for month in months:
month_str = f"{month:02d}"
year_month_int = year * 100 + month # Calculate YYYYMM integer
# Construct URL (remains consistent)
url = f"{URL_BASE}{year}/MMSDM_{year}_{month_str}/MMSDM_Historical_Data_SQLLoader/DATA/"
# Determine filename based on date
if year_month_int >= 202408:
# New format
raw_filename = f"PUBLIC_ARCHIVE#P5MIN_INTERCONNECTORSOLN#FILE01#{year}{month_str}010000.zip"
else:
# Old format
raw_filename = f"PUBLIC_DVD_P5MIN_INTERCONNECTORSOLN_{year}{month_str}010000.zip"
# Encode '#' for the URL
encoded_filename = raw_filename.replace("#", "%23")
zip_path = DATA_DIR / raw_filename # Local path uses the raw filename
# Skip if file already exists locally
if zip_path.exists():
print_and_log(f"{zip_path} already exists. Skipping download.")
else:
try:
# download_file returns the zip_path on success
zip_path = download_file(url, DATA_DIR, raw_filename, encoded_filename)
except RetryError as e:
print_and_log(f"Failed to download {url + encoded_filename} after multiple attempts. Skipping processing for this month.", level=logging.ERROR, err=e)
continue # Skip to the next month/file
# Process the file if download or local existence was successful
if zip_path and zip_path.exists(): # Ensure zip_path exists after download attempt or check
# Pass the year_month integer to process_csv
csv_path = unzip_file(zip_path, DATA_DIR)
if csv_path and csv_path.exists(): # Ensure csv_path exists after unzip attempt
process_csv(csv_path, year_month_int)
# Clean up files
csv_path.unlink(missing_ok=True)
zip_path.unlink(missing_ok=True) # Only delete zip if CSV processing was attempted
print_and_log(f"Cleaned up {zip_path.name} and {csv_path.name}")
elif zip_path.exists():
# If unzip failed but zip exists, perhaps keep zip for inspection?
print_and_log(f"Unzipping or finding CSV failed for {zip_path}. Keeping zip file for inspection.", level=logging.WARNING)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Download and process AEMO P5MIN Interconnector data.")
parser.add_argument("start_year_month", type=str, help="Start year and month in YYYYMM format (e.g., 202301)")
parser.add_argument("end_year_month", type=str, help="End year and month in YYYYMM format (e.g., 202408)")
args = parser.parse_args()
main(args.start_year_month, args.end_year_month)
Key Change:
Removed the message="..." keyword argument from the before_sleep_log calls in both @retry decorators (around lines 95 and 136).
This should resolve the TypeError. Thank you for catching that!
zip_path.stem + ".CSV"
Download Retry: Increased wait time slightly in retry decorator.
Database Connection: Added handling for configuration file not found errors.
Cleanup: Explicitly added a log message after successful cleanup.