File size: 2,919 Bytes
3325433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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"

        # Copy the request content (a ZIP file) to a temporary file
        with tmp_zip_path.open("wb") as f:
            for chunk in r.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)

        # Extract the name of the file we're interested in, there should be
        # only one file in the ZIP archive
        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

        # Extract the file to a temporary location
        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)

        # The text is in ISO-8859-1 encoding
        # We strip spaces before/after all columns
        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)