|
import csv |
|
import tempfile |
|
import zipfile |
|
from pathlib import Path |
|
from typing import Iterator |
|
|
|
import duckdb |
|
import requests |
|
import tqdm |
|
|
|
DUCKDB_SQL = ( |
|
"""COPY (SELECT * FROM read_csv('%s', delim=';', AUTO_DETECT=TRUE)) TO '%s';""" |
|
) |
|
|
|
|
|
def csv_iter(url: str, strip_header: bool = False) -> Iterator[list[str]]: |
|
"""Download France AgriMer RNM CSV file from URL to |
|
output_file.""" |
|
r = requests.get(url, stream=True) |
|
|
|
with tempfile.TemporaryDirectory() as tmp_dir: |
|
tmp_zip_path = Path(tmp_dir) / "tmp.zip" |
|
|
|
|
|
with tmp_zip_path.open("wb") as f: |
|
for chunk in r.iter_content(chunk_size=1024): |
|
if chunk: |
|
f.write(chunk) |
|
|
|
|
|
|
|
zip_file = zipfile.ZipFile(tmp_zip_path) |
|
zip_file_info = zip_file.infolist() |
|
|
|
if len(zip_file_info) != 1: |
|
raise ValueError("Expecting one file in zip") |
|
|
|
filename = zip_file_info[0].filename |
|
tmp_path = Path(tmp_dir) / filename |
|
|
|
|
|
with zip_file.open(filename, "r") as f_in: |
|
with tmp_path.open("wb") as f_out: |
|
while True: |
|
chunk = f_in.read(1024) |
|
if chunk == b"": |
|
break |
|
f_out.write(chunk) |
|
|
|
|
|
|
|
with open(tmp_path, "rt", encoding="ISO-8859-1", newline="") as f_in: |
|
csv_reader = csv.reader(f_in, delimiter=";") |
|
for i, row in enumerate(csv_reader): |
|
if strip_header and i == 0: |
|
continue |
|
yield [col.strip() for col in row] |
|
|
|
|
|
def generate_csv(output_path: Path, start_year: int, end_year: int) -> None: |
|
with open(output_path, "wt") as f_out: |
|
csv_writer = csv.writer(f_out, delimiter=";") |
|
for i in tqdm.tqdm(range(start_year, end_year + 1), desc="years"): |
|
url_template = f"https://visionet.franceagrimer.fr/Pages/OpenDocument.aspx?fileurl=Statistiques%2fmulti-filieres%2fcotations%20des%20produits%20frais%2fCOT-MUL-prd_RNM-A{i:02d}.zip&telechargersanscomptage=oui" |
|
|
|
for item in tqdm.tqdm( |
|
csv_iter(url_template, strip_header=(i != start_year)), desc="rows" |
|
): |
|
csv_writer.writerow(item) |
|
|
|
|
|
def export_parquet(input_path: Path, output_path: Path) -> None: |
|
conn = duckdb.connect(":memory:") |
|
conn.execute(DUCKDB_SQL % (input_path, output_path)) |
|
|
|
|
|
OUTPUT_CSV_PATH = Path("COT-MUL-prd_RNM.csv") |
|
OUTPUT_PARQUET_PATH = Path("COT-MUL-prd_RNM.parquet") |
|
generate_csv(OUTPUT_CSV_PATH, start_year=0, end_year=24) |
|
export_parquet(OUTPUT_CSV_PATH, OUTPUT_PARQUET_PATH) |
|
|