|
| 1 | +import os |
| 2 | +import requests |
| 3 | +import pandas as pd |
| 4 | +from google.cloud import storage |
| 5 | +from dotenv import load_dotenv |
| 6 | +from tqdm import tqdm |
| 7 | +import gzip |
| 8 | +import pyarrow as pa |
| 9 | +import pyarrow.parquet as pq |
| 10 | + |
| 11 | + |
| 12 | +""" |
| 13 | +Pre-reqs: |
| 14 | +1. run `uv sync` from this 'extra' folder (create venv and install dependencies from pyproject.toml) |
| 15 | +2. rename .env-example to .env (not commited thanks to .gitignore) |
| 16 | +3. in .env, |
| 17 | + - set GCP_GCS_BUCKET as your bucket or change default value of BUCKET |
| 18 | + - Set GOOGLE_APPLICATION_CREDENTIALS to your project/service-account json key |
| 19 | + (or don't set it if you use google ADC) |
| 20 | +""" |
| 21 | +# load env vars from .env |
| 22 | +load_dotenv() |
| 23 | + |
| 24 | +# services = ['fhv','green','yellow'] |
| 25 | +init_url = "https://github.com/DataTalksClub/nyc-tlc-data/releases/download/" |
| 26 | +# if not done in .env, switch out the default bucketname |
| 27 | +BUCKET = os.environ.get("GCP_GCS_BUCKET", "dtc-data-lake-bucketname") |
| 28 | + |
| 29 | + |
| 30 | +def download_with_progress(url: str, local_path: str, desc: str = "Downloading"): |
| 31 | + with requests.get(url, stream=True) as r: |
| 32 | + r.raise_for_status() |
| 33 | + total = int(r.headers.get("content-length", 0)) |
| 34 | + # Configure tqdm for bytes |
| 35 | + with ( |
| 36 | + open(local_path, "wb") as f, |
| 37 | + tqdm( |
| 38 | + total=total, |
| 39 | + unit="B", |
| 40 | + unit_scale=True, |
| 41 | + unit_divisor=1024, |
| 42 | + desc=desc, |
| 43 | + ) as bar, |
| 44 | + ): |
| 45 | + for chunk in r.iter_content(chunk_size=1024 * 1024): # 1 MB |
| 46 | + if not chunk: |
| 47 | + continue |
| 48 | + size = f.write(chunk) |
| 49 | + bar.update(size) |
| 50 | + |
| 51 | + |
| 52 | +def csv_to_parquet_with_progress( |
| 53 | + csv_path: str, parquet_path: str, service_color: str, chunksize: int = 100_000 |
| 54 | +): |
| 55 | + # 1) Count rows (gzip-aware) |
| 56 | + with gzip.open(csv_path, mode="rt") as f: |
| 57 | + total_rows = sum(1 for _ in f) - 1 # minus header |
| 58 | + if total_rows <= 0: |
| 59 | + raise ValueError("CSV appears to be empty") |
| 60 | + |
| 61 | + # 2) Read in chunks with fixed dtypes so parquet columns will directly have good types |
| 62 | + # (as we did in module 1 in ingest.py script) |
| 63 | + dtypes = { |
| 64 | + "VendorID": "Int64", |
| 65 | + "RatecodeID": "Int64", |
| 66 | + "PULocationID": "Int64", |
| 67 | + "DOLocationID": "Int64", |
| 68 | + "passenger_count": "Int64", |
| 69 | + "payment_type": "Int64", |
| 70 | + "trip_type": "Int64", # only in green but ignored if missing column |
| 71 | + "store_and_fwd_flag": "string", |
| 72 | + "trip_distance": "float64", |
| 73 | + "fare_amount": "float64", |
| 74 | + "extra": "float64", |
| 75 | + "mta_tax": "float64", |
| 76 | + "tip_amount": "float64", |
| 77 | + "tolls_amount": "float64", |
| 78 | + "ehailfee": "float64", # only in green but ignored if missing column |
| 79 | + "improvement_surcharge": "float64", |
| 80 | + "total_amount": "float64", |
| 81 | + "congestion_surcharge": "float64", |
| 82 | + } |
| 83 | + |
| 84 | + if service_color == "yellow": |
| 85 | + parse_dates = ["tpep_pickup_datetime", "tpep_dropoff_datetime"] |
| 86 | + else: |
| 87 | + parse_dates = ["lpep_pickup_datetime", "lpep_dropoff_datetime"] |
| 88 | + |
| 89 | + reader = pd.read_csv( |
| 90 | + csv_path, |
| 91 | + dtype=dtypes, |
| 92 | + parse_dates=parse_dates, |
| 93 | + compression="gzip", |
| 94 | + chunksize=chunksize, |
| 95 | + low_memory=False, |
| 96 | + ) |
| 97 | + |
| 98 | + writer = None |
| 99 | + |
| 100 | + with tqdm(total=total_rows, unit="rows", desc=f"Parquet {csv_path}") as bar: |
| 101 | + for chunk in reader: |
| 102 | + table = pa.Table.from_pandas(chunk) |
| 103 | + if writer is None: |
| 104 | + writer = pq.ParquetWriter(parquet_path, table.schema) |
| 105 | + else: |
| 106 | + # Optional safety: align to first schema |
| 107 | + table = table.cast(writer.schema) |
| 108 | + writer.write_table(table) |
| 109 | + bar.update(len(chunk)) |
| 110 | + |
| 111 | + if writer is not None: |
| 112 | + writer.close() |
| 113 | + |
| 114 | + |
| 115 | +def upload_to_gcs_with_progress(bucket: str, object_name: str, local_file: str): |
| 116 | + # # WORKAROUND to prevent timeout for files > 6 MB on 800 kbps upload speed. |
| 117 | + # # (Ref: https://github.com/googleapis/python-storage/issues/74) |
| 118 | + # Optional: tune chunk size (must be multiple of 256 KiB) |
| 119 | + storage.blob._MAX_MULTIPART_SIZE = 5 * 1024 * 1024 # 5 MB |
| 120 | + storage.blob._DEFAULT_CHUNKSIZE = 5 * 1024 * 1024 # 5 MB |
| 121 | + |
| 122 | + client = storage.Client() |
| 123 | + bucket_obj = client.bucket(bucket) |
| 124 | + blob = bucket_obj.blob(object_name) |
| 125 | + |
| 126 | + if blob.exists(client): |
| 127 | + print(f"Skipping upload, already in GCS: gs://{bucket}/{object_name}") |
| 128 | + return |
| 129 | + |
| 130 | + file_size = os.path.getsize(local_file) |
| 131 | + |
| 132 | + with open(local_file, "rb") as f: |
| 133 | + with tqdm.wrapattr( |
| 134 | + f, |
| 135 | + "read", |
| 136 | + total=file_size, |
| 137 | + miniters=1, |
| 138 | + unit="B", |
| 139 | + unit_scale=True, |
| 140 | + unit_divisor=1024, |
| 141 | + desc=f"Uploading {os.path.basename(local_file)}", |
| 142 | + ) as wrapped_file: |
| 143 | + blob.upload_from_file( |
| 144 | + wrapped_file, |
| 145 | + size=file_size, # important so the library knows total bytes |
| 146 | + ) |
| 147 | + |
| 148 | + print(f"Uploaded to GCS: gs://{bucket}/{object_name}") |
| 149 | + |
| 150 | + |
| 151 | +def web_to_gcs(year, service): |
| 152 | + client = storage.Client() |
| 153 | + bucket_obj = client.bucket(BUCKET) |
| 154 | + |
| 155 | + for i in tqdm(range(12), desc=f"{service} {year}", unit="month"): |
| 156 | + month = f"{i + 1:02d}" |
| 157 | + |
| 158 | + csv_file_name = f"{service}_tripdata_{year}-{month}.csv.gz" |
| 159 | + parquet_file_name = csv_file_name.replace(".csv.gz", ".parquet") |
| 160 | + object_name = f"{service}/{parquet_file_name}" |
| 161 | + |
| 162 | + # 1) Check if parquet already in GCS |
| 163 | + blob = bucket_obj.blob(object_name) |
| 164 | + if blob.exists(client): |
| 165 | + print(f"Already in GCS, skipping: gs://{BUCKET}/{object_name}") |
| 166 | + continue |
| 167 | + |
| 168 | + # 2) Check if CSV already downloaded locally |
| 169 | + if os.path.exists(csv_file_name): |
| 170 | + print(f"CSV already exists locally, skipping download: {csv_file_name}") |
| 171 | + else: |
| 172 | + request_url = f"{init_url}{service}/{csv_file_name}" |
| 173 | + download_with_progress( |
| 174 | + request_url, csv_file_name, desc=f"Downloading {csv_file_name}" |
| 175 | + ) |
| 176 | + |
| 177 | + # 3) Check if Parquet already exists locally |
| 178 | + if os.path.exists(parquet_file_name): |
| 179 | + print( |
| 180 | + f"Parquet already exists locally, skipping conversion: {parquet_file_name}" |
| 181 | + ) |
| 182 | + else: |
| 183 | + csv_to_parquet_with_progress(csv_file_name, parquet_file_name, service) |
| 184 | + print(f"Parquet: {parquet_file_name}") |
| 185 | + |
| 186 | + # 4) Upload with per-byte progress bar |
| 187 | + upload_to_gcs_with_progress(BUCKET, object_name, parquet_file_name) |
| 188 | + |
| 189 | + |
| 190 | +web_to_gcs("2019", "green") |
| 191 | +web_to_gcs("2020", "green") |
| 192 | +web_to_gcs( |
| 193 | + "2021", "green" |
| 194 | +) # will fail when reaching 08 (normal, file does not exists in github :) |
| 195 | +# web_to_gcs("2019", "yellow") |
| 196 | +# web_to_gcs("2020", "yellow") |
| 197 | +# web_to_gcs("2021", "yellow") # will fail when reaching 08 (normal, file does not exists in github :) |
0 commit comments