-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathload_data.py
More file actions
78 lines (63 loc) · 2.21 KB
/
Copy pathload_data.py
File metadata and controls
78 lines (63 loc) · 2.21 KB
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
import os
import pandas as pd
from sqlalchemy import create_engine
from kaggle.api.kaggle_api_extended import KaggleApi
import streamlit as st
import json
secrets = st.secrets["postgres"]
# Set up Kaggle API credentials from Streamlit secrets
kaggle_secrets = st.secrets["kaggle"]
os.environ["KAGGLE_USERNAME"] = kaggle_secrets["username"]
os.environ["KAGGLE_KEY"] = kaggle_secrets["key"]
# ---- SETTINGS ----
KAGGLE_DATASET = "arianazmoudeh/airbnbopendata"
DOWNLOAD_DIR = os.path.join(os.getcwd(), "kaggle_data")
CSV_FILE = "Airbnb_Open_Data.csv"
def download_dataset():
api = KaggleApi()
api.authenticate()
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
print("Downloading dataset from Kaggle...")
api.dataset_download_files(KAGGLE_DATASET, path=DOWNLOAD_DIR, unzip=True)
print("Download complete.")
# load csv into postgres
def load_to_postgres():
csv_path = os.path.join(DOWNLOAD_DIR, CSV_FILE)
if not os.path.exists(csv_path):
raise FileNotFoundError(f"{csv_path} not found. Check file name inside {DOWNLOAD_DIR}")
print("CSV conversion to dataframe")
df = pd.read_csv(csv_path)
# --- Clean column names to snake_case lowercase ---
df.columns = (
df.columns.str.strip()
.str.lower()
.str.replace(" ", "_")
)
# set id as index if exists
if "id" in df.columns:
df.set_index("id", inplace=True)
# clean price and service_fee columns
if "price" in df.columns:
df["price"] = (
df["price"]
.astype(str)
.str.replace("[$,]", "", regex=True)
.astype(float)
)
if "service_fee" in df.columns:
df["service_fee"] = (
df["service_fee"]
.astype(str)
.str.replace("[$,]", "", regex=True)
.astype(float)
)
print(f"Loaded {len(df):,} rows from CSV.")
# connect to postgres
conn_str = f'postgresql://postgres:{secrets["PASSWORD"]}@localhost:5432/airbnb_kaggle'
engine = create_engine(conn_str)
df.to_sql('airbnb_kaggle', engine, if_exists="replace", index=True, chunksize=1000)
print("Data successfully loaded into Postgres.")
# RUN
if __name__ == "__main__":
download_dataset()
load_to_postgres()