data_downloader.py

The program is built on a metadata-drive architecture. Instead of hardcoding API endpoints or database schemas, the systesm read from a sources.json file. This allows us to add new Census products (or products from other sources) simply by updating the json file.
The interface is divided into five functional "Focus Zones" to manage the complexity of geographic data:
-
Data Source (Top Bar 1): Horizontal selection of the Census product (e.g., ecnbasic).
-
Scope (Top Bar 2): Horizontal selection of granularity: this is geographic for Census-based data (ECN, CBP, NES, ACS the options are National, State, or County) while this is chunks for BLS data (CEX, CPI, PPI).
-
Actions (Middle Left): Vertical menu for Download, Upload, Backup, and Restore.
-
List 1 (Middle Center): For Census data , this is a scrollable list of US States with status icons. For BLS data, this is a list of timeseries.
-
List 2 (Middle Right): For Census data, this is a dynamic drill-down showing residency status for counties in the selected state. BLS data provides metadata for the series.
The program utilizes the requests library with a retry strategy to fetch data from the Census API.
Before data hits the database, it is "cleaned" into a Tab-Separated Values (TSV) format.
-
Null Handling: Census "None" or empty values are explicitly converted to the string NULL.
-
Normalization: Geographic FIPS codes are padded (e.g., 1 becomes 01) to match the reference schema.
To handle millions of rows, the program avoids standard INSERT statements, which are slow.
INSERT INTO production_table SELECT * FROM temporary_table
ON CONFLICT (unique_hash) DO NOTHING;
The Backup and Restore system acts as a manual version control for your datasets.
-
Snapshots: The Backup action uses a "Shadow Table" approach (table_name_bk). It performs a server-side clone of the production data.
-
Restoration: The Restore action drops the production table and reinstates the backup. Crucial: The program manually reconstructs the UNIQUE index on the unique_hash column after a restore, as cloning data alone does not copy table constraints.
| Key |
Action |
TAB |
Cycle focus between the 5 UI Zones |
Arrows |
Navigate within the active zone (horizontal (left/right) for bars, vertical (up/down) for lists) |
SPACE |
Queue a state or county for batch processing |
C |
Select / deselect ALL counties in the highlighted state |
ENTER |
Execute the highlighted action (sync, backup or restore) |
Q |
Gracefully exit the program |
-
.env: Must contain DB_NAME, DB_USER, DB_PASS, DB_HOST, and CENSUS_API_KEY.
-
sources.json: The metadata configuration file.
-
PostgreSQL Tables:
- Raw Schema: The raw schema must contain the tables defined in the JSON, each with a temporary counterpart and a backup version (e.g.,
ecn_2022_st and ecn_2022_st_tmp and ecn_2022_st_bk)
- Reference Schema: Tables with FIPS codes for the states and counties.
- Initialization
- Load environmental variables
- Set up logging file:
data_downloader.log
- Global Data Loading
- Census Reference Loader Functions
-
load_states_from_db()
Fetches the master list of 50 states (plus territories) from the reference.states_fips table. This populates the central UI panel.
-
load_counties_from_db()
Fetches the complete national directory of counties (~3,200 records) from reference.county_fips. This is stored in memory to allow for instant filtering when browsing states.
- BLS Metadata Context Loader Functions
-
locate_available_chunks(chunks_dir)
Scans the targeted BLS directory for split JSON metadata chunk files.
-
load_series_from_chunk(chunk_path)
Loads series items and metadata records from a specified local catalog chunk.
- Database State Synchronization Lookups
-
get_synced_states(geo_meta)
Queries the active production table to see which states already have data. It returns a set of FIPS codes used to turn UI icons Green (the "Green Code" logic).
-
get_synced_counties(table, state_fips)
Performs a targeted query for a specific state to identify which of its counties are already in the database. This is used for the "drill-down" status panel.
* `get_synced_bls_series(source_name, series_ids)`
Verifies which series identifiers are already tracked inside production tables. Batches lookups into chunks of 500 rows to prevent query parsing threshold breaks.
- Resuable Master Database Backup/Resotre Layer
-
backup(stdscr, geo_meta)
Clones the current production table into a shadow table (suffixed with _bk). This uses server-side cloning for near-instant snapshots of millions of rows.
-
restore_backup(stdscr, geo_meta)
The "Undo" function. It drops the current production table and replaces it with the backup. It also manually restores the UNIQUE constraints that are lost during table cloning.
-
extract_column_label(label_string)
Extracts the column (or cohort) name in the ACS data.
- Core Pipeline Pipes: Downloaders and Intermediate Loaders
-
extract_data_acs5(stdscr, s_fips, c_fips, source_meta, geo_meta, s_abbr)
The core engine for ACS (American Community Survey) data. This data is significantly different from the other datasets.
-
extract_data_standard(stdscr, s_fips, c_fips, source_meta, geo_meta, s_abbr)
The core engine. It handles:
-
upload_data_acs5(stdscr, s_abbr, source_meta, geo_meta)
Transforms multi-index demographic summary files into stacked relational shapes. Streams outputs to a local disk data.tsv buffer and implements binary COPY operations.
-
upload_data_standard(stdscr, s_abbr, source_meta, geo_meta)
Flattens and bulk-loads standard layout business and economic datasets (CBP, ECN).
-
execute_bls_extraction(stdscr, source_name, api_url, series_data, chunk_filename, start_year="2016", end_year="2026")
Extracts time-series arrays from BLS endpoints for elements mapped inside a target chunk. Saves the output payload to a unique file specific to the active chunk name.
-
execute_bls_upload(stdscr, source_name, chunk_filename)
Transforms chunk-specific BLS raw data JSON caches into clean time-series rows and loads them into the database using high-speed binary COPY streams. Safely downcasts missing data hyphen string symbols ('-') into database NULL markers.
- Action Handler
run_action(stdscr, selections, selected_states, selected_counties, geo_meta)
The "Switchboard." It interprets which action is highlighted in the menu and builds the work queue (determining if it should process one county, one state, or a batch of states). Determines which ETL pipeline to run (ACS or main).
- Main Controller Window Management
-
draw_ui(stdscr, status, details)
A "blocking" screen overlay. It hides the dashboard and shows a progress bar or status message (e.g., "SYNCING 5/50") during heavy network or database tasks.
-
show_popup(stdscr, title, body)
Displays a modal box summarizing results.
-
draw_interface(stdscr, focus_idx, sel, scroll, c_scroll, synced_st, selected_st, selected_co, synced_co)
The primary rendering engine. It draws all 5 zones of the dashboard, calculates scroll positions, and applies color pairs based on the sync status of the data.
-
main(stdscr)
The entry point. It initializes the curses environment, manages the focus_idx (which zone is active), and listens for keyboard interrupts to update the program state.
Selection Logic Hierarchy
When you hit ENTER to sync, the program decides what to download based on this priority:
-
County Queue: If any counties were selected via the C key.
-
State Queue: If any states were checked via SPACE.
-
Active Highlight: If nothing is checked, it syncs only the state/level currently under the cursor.
flowchart TD
start(("start"))
--> dotenv["Load environmental variables"]
--> raw_data_file["make `raw_data` file if it doesn't exist"]
--> logging_file["set up logging"]
--> source["read `sources.json` file"]
--> raw_data_source["make directories for each source"]
--> load_states[["state_info = load_states_from_db()"]]
--> load_counties[["county_master = load_counties_from_db()"]]
--> main_loop{main_loop}
-- true --> main_loop
-- false --> stop(("stop"))
Indentifies all states in reference schema: reference.states_fips
Returns: a dataframe with columns ['fips_codes', 'state_name', 'state_abbr']
flowchart TD
start(("start"))
--> try{try-except}
-- try
--> connect[("database connect")]
--> state_codes[("SELECT distinct state codes FROM reference.states_fips\nORDER BY state_name;")]
--> dataframe["save query result as `df`"]
--> close_connection[("close connection")]
--> stop(("return df (a dataframe)"))
try -- except
--> log_error>"ERROR: state reference load failure"]
--> empty(("return empty set as a dataframe"))
Identifies all counties from reference schema: reference.county_fips
Returns: a dataframe with columns ['state_fips', 'county_fips', 'county_name'].
flowchart TD
start(("start"))
--> try{try-except}
-- try --> connect[(connect to database)]
--> query[("SELECT distinct county codes FROM reference.county_fips\nORDER BY state_fips, county_name;")]
--> df["save result of query as a dataframe"]
--> close_connection[("close connection")]
--> stop(("return dataframe"))
try -- except
--> log_error>"ERROR: county reference load failure"]
--> except_stop(("return empty dataframe"))
Scans the targeted BLS directory for split JSON metadata chunk files.
Args:
- chunks_dir (str): Relative directory path holding partitioned catalogs.
Returns:
- list: A sorted list of filename strings matching target definitions (e.g., '.json').
flowchart TD
start(("start"))
--> if{"if chunks_dir does not exist \n or if the path does not exist"}
-- true --> return_empty(("return empty set"))
if -- false --> return_list(("return sorted list of json file names"))
Loads series items and metadata records from a specified local catalog chunk.
Args:
- chunk_path (str): Filepath location pointing to the chunk target.
Returns:
- list: A parsed collection of dictionary objects tracking individual series metrics.
flowchart TD
start(("start"))
--> if{"if chunk_path does not exist"}
-- true --> return_empty(("return empty list"))
if -- false
--> try_except{"try/except"} -- try
--> read_file[read file as dictionary]
--> return_dict(("return dictionary"))
try_except -- except
--> log_error>"ERROR: failed to read chunk mapping"]
--> return_empty1(("return empty list"))
Identifies states already in database
Args:
- geo_meta (dict): Visual scope mapping metadata containing target table layouts.
Returns:
- set: a collection of 2 digit fips strings of the states present in the database
flowchart TD
start((start))
--> conn_none
--> try_except{"try/except"} -- try
--> define_conn
--> connect[(connect to database)]
--> table
--> if_national{if national level table}
-- false --> query["QUERY distinct state_fips in table"]
--> res[convert to strings]
--> return_res((return res))
--> finally
--> if_conn{if conn exists} -- true
--> close_connection[("close connection")]
--> stop(("stop"))
if_conn -- false
--> stop
if_national -- true -->
query_us["QUERY if any entries in table"]
--> if_results{if results exist}
-- true --> return_us(("return set {'00'}"))
--> finally
if_results -- false --> return_empty((return empty set))
--> finally
try_except -- except
--> return(("return empty set"))
--> finally
Identifies which counties within a specific state are already present in database
Args:
- table (str): Production data table tracking spatial metric assignments.
- state_fips (str): 2-digit parental state boundary restriction constraint code.
Returns:
- set: a collection of 3-digit county fips strings
flowchart TD
start(("start"))
--> conn_none
--> try{try/except} -- try
--> connection
--> connect[("connect to database")]
--> query[("QUERY distinct county_fips for specific state,\n pad results to 3 characters")]
--> return(("return result as a set of strings"))
--> finally
--> if_conn{if conn exists} -- true
--> close_connection[("close connection")]
--> stop(("stop"))
if_conn -- false
--> stop
try -- except --> return_empty(("return empty set"))
--> finally
Verifies which series identifiers are already tracked inside production tables.
Batches lookups into chunks of 500 rows to prevent query parsing threshold breaks.
Args:
- source_name (str): Core target data survey layout handle (e.g., 'cex', 'cpi').
- series_ids (list): Array string blocks holding individual series tokens.
Returns:
- set: A collection of plain strings reflecting synced keys found in the database.
flowchart TD
start(("start"))
--> if_no_series_ids{"if series_ids does not exist"} -- true
--> return_empty(("return empty set"))
if_no_series_ids -- false
--> conn_none
--> try{"try/except"} -- try
--> define_conn
--> connect_db[("connect to database")]
--> define_table
--> define_synced
--> for_loop{"for each batch of 500 series"} -- batch
--> define_batch
--> search_table[("search table for series_id")]
--> update_synced["add found series_id to synched"]
--> another_batch{"another batch?"} -- true
--> for_loop
another_batch -- false
--> return_synced(("return synced"))
--> finally
--> if_conn{if conn exists} -- true
--> close_connection[("close connection")]
--> stop(("stop"))
if_conn -- false
--> stop
try -- except
--> return_empty_set(("return empty set"))
--> finally
Creates a backup of the production table
Args:
- stdscr (window): Master curses interface screen context window.
- schema_table_name (str): Full dot-notated destination table name (e.g., 'raw.bls_cpi').
flowchart TD
start(("start"))
--> try{"try / except"}
-- try --> define_var["table name, backup"]
--> ui_back[/"inform user: BACKING UP"/]
--> connect_db[("connect to database")]
--> drop_table[("DROP old backup table if it exists")]
--> create_bk[("CREATE backup table by cloning production table")]
--> close_connection
--> log_info>"INFO: Database backup complete"]
--> stop(("stop"))
try -- except --> log_error>"ERROR: Backup failure"]
--> stop
Overwrites an active production database table layout from the latest backup clone.
Re-applies unique constraints/hashes dropped during raw server-side table duplication.
Args:
- stdscr (window): Curses active system terminal viewport component context.
- schema_table_name (str): Full dot-notated target table path (e.g., 'raw.bls_cex').
- is_bls (bool): Set to True for BLS datasets to correctly re-provision the composite unique_hash string index.
flowchart TD
start(("start"))
--> try{"try/except"} -- try
--> define_backup_table
--> inform_user[\"RESTORING"\]
--> define_conn
--> connect_cb[("connect to database")]
--> drop_table[("DROP table if it exists")]
--> create_table[("CREATE table from backup")]
--> raw_table_suffix
--> if_bls -- true
--> add_bls_constraint[("add unique_hash constraint")]
--> close_connection
--> log_info>"INFO: database restore complete"]
--> stop(("stop"))
if_bls -- false
--> add_constraint[("add unique_hash constraint")]
--> close_connection
try -- except
--> log_error>"ERROR: restore failure"]
--> stop
Processes the data extraction, transformation, and loading processing for the ACS data (since it's different from the other data sets).
Returns: number of rows merged
flowchart TD
start(("start"))
--> success_true
--> for_loop["each subject_table in the list of subject tables"]
-- item_in_list
--> name_data_files
--> if_geo_us{"if geo is National"}
-- true --> api_us[url = ]
--> draw_ui_downloading("display: DOWNLOADING ACS5")
if_geo_us -- false
--> if_geo_state{"if geo is State"}
-- true --> api_state[url]
--> draw_ui_downloading
if_geo_state -- false
--> api_county[url]
--> draw_ui_downloading
--> log_start>LOG: fetch start]
--> start_time
--> try_api{"try/except"}
-- try --> request
--> write_raw_data[/write raw data in chunks/]
--> calucate_duration
--> calcuate_speed
--> log_success>"INFO: fetch success, table, size, speed"]
--> another_table{"another table?"} -- true
--> for_loop
another_table -- false
--> return_success(("return success status"))
try_api -- except
--> log_error>"ERROR: table, error"]
--> success_false
--> another_table
Donwloads standard (census) data.
Returns: number of rows merged into database
flowchart TD
start(("start"))
--> name_data_files
--> base_vars
--> if_geo_us{if National}
-- true
--> api_us[url]
--> draw_ui_download[["draw_ui(DOWNLOADING)"]]
if_geo_us -- false
--> if_geo_state -- true
--> api_state[url]
--> draw_ui_download
if_geo_state -- false
--> api_county[url]
--> draw_ui_download
--> log_start_etl>LOG: fetch start]
--> start_time
--> try_except{try/except}
-- try --> request_url
--> raise_status
--> write_raw_data[/Write raw data/]
--> log_download>LOG: download success]
--> read_raw_data[\read raw data\]
--> write_tsv[force string type, join with tab character, forces NULLS, new line]
--> calculate_duration
--> calculate_speed
--> log_success>"INFO: fetch success, sources, size, speed"]
--> return_true(("return TRUE"))
try_except -- except
--> log_error>"ERROR: fetch failure"]
--> reutnr_false(("return FALSE"))
Transforms multi-index demographic summary files into stacked relational shapes.
Streams outputs to a local disk data.tsv buffer and implements binary COPY operations.
Args:
- stdscr (window): Curses window engine instance.
- s_abbr (str): Target identification alphanumeric state locator context handle.
- source_meta (Series): Parameter settings defining the variable constraint matrices.
- geo_meta (dict): Selected geography scale definition options properties map.
Returns:
- int: Cumulative count indicating newly updated or appended production table records.
flowchart TD
start(("start"))
--> total_records_zero
--> tsv_file
--> for_loop{"for each subject table in list"} -- subject_table
--> data_file
--> if_data_file_not_exist{"if data_file does not exist"} -- true
--> continue
--> another_subject_table{"another subject table in list?"} -- true
--> for_loop
another_subject_table -- false
--> return_total_records(("return total_records"))
if_data_file_not_exist -- false
--> draw_ui[\"TRANSFORM & LOAD"\]
--> try{"try/except"} -- try
--> read_data_file
--> if_read_error{if error in reading file} -- true
--> continue1["continue"]
--> another_subject_table
if_read_error -- false
--> headers
--> dataframe
--> id_cols
--> append_extra_geo_cols
--> df_set_index
--> new_columns
--> for_each_column_loop[["for each column loop (see diagram below)"]]
--> define_columns[define multiindex columns]
--> stack_df
--> write_csv
--> connect_db[("connect to database")]
--> truncate_table[("TRUNCATE table_tmp")]
--> open_csv_file
--> copy_from_csv[("COPY table_tmp from csv file")]
--> insert_table[("INSERT INTO table SELECT sols FROM table_tmp\n ON CONFLICT (unique_hash) DO NOTHING")]
--> increase_total_records
--> close_connection[("close connection")]
--> another_subject_table
try -- except
--> log_error>"ERROR: ACS5 transformation exception"]
--> another_subject_table
Column LOOP*
flowchart TD
for_each_column_loop -- col
--> if_EA{"if endswith EA"} -- true
--> metric_estimate_flag
--> append_to_new_columns
--> another_column{"another column?"} -- true
--> for_each_column_loop
if_EA -- false
--> if_MA{"if ends with MA"} -- true
--> metric_margin_flag
--> append_to_new_columns
if_MA -- false
--> if_E{"if ends with E"} -- true
--> metric_estimate
--> append_to_new_columns
if_E -- false
--> if_M{"if ends with M"} -- true
--> metric_margin
--> append_to_new_columns
if_M -- false
--> continue2
--> another_column
another_column -- false
--> loop_ends
Flattens and bulk-loads standard layout business and economic datasets (CBP, ECN).
Args:
- stdscr (window): Master graphics engine viewport context window tracking token.
- s_abbr (str): Target textual abbreviation indicating the current tracking geography scope.
- source_meta (Series): Configuration metadata dictionary item mapping profiles.
- geo_meta (dict): Relational database storage structure configurations attributes map.
Returns:
- int: Cumulative count tracking newly synchronized rows saved to database storage.
flowchart TD
start(("start"))
--> setup["define data_file, tsv_file"]
--> if_path_not_exists{"if data_file path does not exist"} -- true
--> return_zero(("return zero"))
if_path_not_exists -- false
--> draw_ui[/"TRANFORM & UPLOAD"/]
--> try{"try / except"} -- try
--> read_data_file
--> write_tsv_file
--> connect_db[("connect to database")]
--> define_table_cols
--> truncate_tmp[("TRUNCATE table_tmp")]
--> copy_tmp[("COPY table_tmp FROM tsv_file")]
--> insert[("INSERT INTO table FROM table_tmp\nON CONFLICT (unique_hash) DO NOTHING")]
--> merge_count
--> close_connection[("close connection")]
--> return_merge_count(("return merge_count"))
try -- except
--> log_error>"ERROR: standard load exception"]
Extracts time-series arrays from BLS endpoints for elements mapped inside a target chunk. Saves the output payload to a unique file specific to the active chunk name.
Includes automatic retries for transient read timeouts and network drops.
Args:
- stdscr (window): Live dashboard display interface frame tracking pointer.
- source_name (str): Survey dataset string label index token (e.g., 'ppi', 'cex').
- api_url (str): Target HTTP endpoint URL for post payload submissions.
- series_data (list): Parsed series index mappings tracking active metadata properties.
- chunk_filename (str): The filename of the active highlighted chunk (e.g.,
combined_cpi_chunk_1.json).
- start_year (str): Lower chronological bound constraints parameters token.
- end_year (str): Upper chronological bound constraints parameters token.
Returns:
- bool: True if extraction processes finished cleanly without quota block terminations.
flowchart TD
start(("start"))
--> setup["define bls_key, chunk_size, series_ids, id_sub_batches, make output_dir, etc"]
--> log_start>"INFO: Fetch Start"]
--> start_time
--> total_bytes_downloaded_zero
--> max_retries
--> session
--> batch_loop{for each batch} -- batch
--> draw_ui_batch[/"ETRACTING BLS"/]
--> payload_setup
--> log_batch>"INFO: api request for dataset, chunk file, batch"]
--> batch_success_false
--> attempt_loop{"attempt loop"}
--> start_batch_time
--> try{"try / except"} -- try
--> session_post
--> session_status
--> response_bytes
--> add_total_bytes_downloaded
--> response_json
--> duration_calucation
--> if_succeed{"if status is REQUEST_SUCCEEDED"} -- true
--> append_result_to_allresponses
--> log_success>"INFO: fetch success"]
--> batch_success_true
--> break_attempt_loop
--> if_not_success{"if not success and other conditions"} -- true
--> break_batch_loop
--> final_output_path
if_not_success -- false
--> sleep1
--> another_batch{"another batch?"} -- true
--> batch_loop
another_batch -- false
--> final_output_path
--> try2{"try / except"} -- try
--> dump_all_responses
--> calucate_total_duration
--> download_mb
--> log_complete>"INFO: extration loop complete"]
--> return_success(("return success"))
if_succeed -- false
--> get_message
--> log_error>"ERROR: bls server error"]
--> if_daily_quota_exhausted{"if daily quota exhausted"} -- true
--> log_critical>"CRITICAL: quota exhausted"]
--> success_false
--> break_attempt_loop
try -- except_timeout
--> calcuate_duration
--> log_warning>"WARNING: fetch timeout"]
--> if_attempt_less_max{"if attempt is less than max"} -- true
--> sleep2
--> another_attempt{"Another attempt?"} -- true
--> attempt_loop
another_attempt -- false
--> if_not_success
if_attempt_less_max -- false
--> log_max_retries>"ERROR: fetch failed after retries"]
--> set_success_false
--> another_attempt
try -- except_Exception
--> calculate_batch_duration
--> log_batch_error>"ERROR: fetch failure"]
--> except_success_false
--> break_attempt_loop
try2 -- except
--> log_error2>"ERROR: metadata write crash"]
--> success_false2
--> return_success
Transforms chunk-specific BLS raw JSON caches into text-based staging rows,extracts footnote metadata (codes and text), and loads data via COPY streams.
Preserves the generated UUID 'id' from the staging table to the primary table and applies conditional ON CONFLICT logic to handle revisions, preliminary ('P'), initial ('I'), estimated ('E'), and corrected ('C') data updates.
Args:
- stdscr (window): Curses interactive window system active viewport.
- source_name (str): Operational survey registry key parameter (e.g., 'cpi').
- chunk_filename (str): Filename of the active highlighted chunk (e.g., 'combined_cpi_chunk_1.json').
Returns:
- int: Total row count added or updated in production storage.
flowchart TD
start(("start"))
--> setup
--> if_path_exists{"if raw_data_path does not exists"} -- true
--> log_warning>"WARNING: upload aborted"]
--> return_zero(("return zero"))
if_path_exists -- false
--> start_time
--> draw_ui[/"BLS TRANSFORMATION"/]
--> log_start>"INFO: Load start"]
--> try{"try / except"} -- try
--> read_raw_data
--> setup_counts
--> chunk_loop{"for each chunk"} -- chunk
--> if_results_series_present{"if chunk has results that contain series"} -- true
--> series_loop{for each series} -- series
--> sereis_id
--> increment_total_series_processed
--> row_loop -- each row
--> process["process year, period, raw value"]
--> value_string
--> footnote_extraction_layer[["foootnote extraction layer"]]
--> compose_unique_hash
--> append_flat_records
--> increment_total_raw_rows
--> another_row{"another row?"} -- true
--> row_loop
another_row -- false
--> another_series{"another series?"} -- true
--> series_loop
another_series -- false
--> another_chunk{"another chunk?"} -- true
--> chunk_loop
if_results_series_present -- false
--> another_chunk
another_chunk -- false
--> if_no_flat_records -- true
--> log_no_records>"WARNING: load cancelled"]
--> return_zero1(("return zero"))
if_no_flat_records -- false
--> log_transformation_complete>"INFO: transform complete"]
--> flat_records_dataframe
--> write_dataframe_to_tsv_file
--> log_ingest_begins>"INFO: database ingest begins"]
--> connect_db[("connect to database")]
--> truncate_table[("TRUNCATE table_tmp")]
--> copy_table[("COPY table_tmp FROM tsv_file")]
--> row_count
--> upsert_table[("INSERT INTO table FROM table_tmp\n ON CONFLICT DO UPDATE SET **** WHERE footnote codes conditions")]
--> merge_count
--> close_connection[("close connection")]
--> if_tsv_file_exists{"if tsv file exists"} -- true
--> remove_tsv_file
--> calculate_duration
if_tsv_file_exists -- false
--> calculate_duration
--> log_upload>"INFO: load complete"]
--> return_merge_count(("return number of merged rows"))
try -- except
--> log_except>"ERROR: load failure"]
--> return_zero2(("return zero"))
Intercepts and routes front-end TUI click triggers to appropriate backend data loops.
Distinguishes operational workflows contextually using the asset source 'type'.
Args:
- stdscr (window): Live component frame window handler object instance.
- sel (dict): Active dashboard coordinate focus index selectors map dictionary.
- selected_st (set): Active user-selected multi-index state FIPS codes array context.
- selected_co (set): Active user-selected multi-index county tracking tuple coordinates.
- series_data (list): Loaded structural data series dictionaries (BLS contexts only).
- chunks_list (list): Identified file catalog tokens present inside targeted subdirectories.
Returns:
- tuple: Multi-element set variables refreshing front-end tracking indicators vectors.
flowchart TD
start(("start"))
--> src["use selections to retrive source details"]
--> if_census{"if source type is census"} -- true
--> census_flow[["census flow channels"]]
if_census -- false
--> if_bls{"if source type is bls"} -- true
--> bls_flow[["bls flow channels"]]
flowchart TD
census_flow[["Census flow channels"]]
--> geo
--> queue
--> if_action_0{"if action is 0"} -- true
--> download_data
--> queue_loop{"for state, county in queue"}
--> try0{"try / except"} -- try
--> abbr["get state abbreviation"]
--> if_acs5{"if sourc etype is acs5"} -- true
--> extract_data_acs5[["extract_data_acs5(stdscr, s, c, src, geo, abbr)"]]
--> show_popup[["show_popup(stdscr, COMPLETE, Ingested raw JSON profiles.)"]]
--> clear_selected_states_counties
--> return_synced_states_counties(("return synced counties and states"))
if_acs5 -- false
--> extract_data_standard[["extract_data_standard(stdscr, s, c, src, geo, abbr)"]]
--> show_popup
try0 -- except
--> abbr_us
--> if_acs5
if_action_0 -- false
--> if_action_1 -- true
--> upload_data
--> total_zero
--> state_loop{"for state in queue"}
--> try1 -- try
--> abbr1["get state abbreviation"]
--> if_acs5_1{"if acs5"} -- true
--> upload_data_acs5[["upload_data_acs5\n returns number of merged rows"]]
--> increase_total
--> if_total_greater_zero{"if total > 0"} -- true
--> backup_table1[["backup_table"]]
--> show_popup1[["show_popup(stdscr, SUCCESS, merged total rows)"]]
--> clear_selected_states_counties
try1 -- except
--> abbr_us_1
--> if_acs5_1
if_acs5_1 -- false
--> upload_data_standard[["upload_data_standard\n returns number of merged rows"]]
--> increase_total
if_action_1 -- false
--> if_action_2 -- true
--> backup_table
--> clear_selected_states_counties
if_action_2 -- false
--> if_action_3 -- true
--> restore_backup
--> clear_selected_states_counties
if_action_3 -- false
--> clear_selected_states_counties
flowchart TD
census_flow[["BLS flow channels"]]
--> target_bls_table
--> active_chunk_name
--> if_action_0{"if action is 0"} -- true
--> download_data
--> execute_bls_extraction[["execute_bls_extraction"]]
--> show_popup_0[["show_popup(stdscr, BLS fetch done, ...)"]]
--> return_zero(("return two empty sets"))
if_action_0 -- false
--> if_action_1 -- true
--> upload_data
--> execute_bls_upload[["execute_bls_upload\n returns number of uploaded rows"]]
--> if_total_greater_zero{"if count > 0"} -- true
--> backup_table1[["backup_table"]]
--> show_popup1[["show_popup(stdscr, BLS merge done, ...)"]]
--> return_zero
if_total_greater_zero -- false
--> backup_table1
if_action_1 -- false
--> if_action_2 -- true
--> backup_table2[["backup_table"]]
--> show_popup2[["show_popup(stdscr, BLS backup success, ...)"]]
--> return_zero
if_action_2 -- false
--> if_action_3 -- true
--> restore_backup[["restore_table_backup"]]
--> show_popup3[["show_popup(stdscr, BLS restore success, ...)"]]
--> return_zero
if_action_3 -- false
--> return_zero
Renders a clean, full-screen status update overlay during blocking I/O tasks.
Args:
- stdscr (window): Curses active system terminal viewport component context.
- status (str): The primary active operation state string (bolded header).
- details (str): Supplementary text tracing current row metrics or paths.
¶ def show_popup(stdscr, title, body)
Renders an informational overlay modal prompt dialog block over the UI workspace grids.
Args:
- stdscr (window): Master graphics engine framework viewport handle wrapper tracking token.
- title (str): Bold header string phrase printing at top of card container.
- body (str): Plain text tracking description message body filling informational areas bounds.
Renders the layout structures and components forming the active 5-zone terminal grid interface.
Handles geometric canvas clipping calculations based on the terminal window limits.
Args:
- stdscr (window): Curses master output viewport panel window component block context tracking pointer.
- focus_idx (int): Global index coordinates tracking the currently focused interactive component zone.
- sel (dict): System coordinate positional index settings dictionary tracking active row assignments.
- chunks (list): Discovered JSON filename mappings entries cached inside localized directory channels.
- series (list): Dictionary item listings loaded from active chunk files containing individual metadata specifications.
- synced_st (set): 2-digit state FIPS identifiers codes confirming localized integration within database schemas.
- selected_st (set): Multi-index operational list storage containing checked state entries.
- selected_co (set): Multi-index tracking parameters layout array containing checked county entry coordinates tuples.
- synced_co (set): 3-digit localized county identity vectors confirming relational integration within target databases.
- synced_bls_ids (set): Explicit strings verifying active index alignment items saved inside database storage schemas.
- scroll (int): Numerical counter tracing top positioning indices offsets for focus zone 3 scroll arrays.
- c_scroll (int): Top index tracking position offsetting row scroll limits inside focus zone 4 structural windows.
- detail_scroll (int): Positional row scroll offset counter tracking metric context lists components attributes mappings.
¶ main(stdscr)
Primary orchestration display thread running loop initialized by curses wrapper processes. Captures continuous keystrokes to evaluate focus panel movements and layout scrolls.
Args:
* stdscr (window): Master application canvas reference window context token block.
flowchart TD
start(("start"))
--> set_up_curses_colors
--> set_selections
--> set_initial_source
--> if_census{"if type census"} -- true
--> synched_state[["get_synced_states"]]
--> while_loop{"while True"} -- true
--> set_source
--> sync_source_status("sync states/counties or series")
--> draw_interface_1[["draw_interface"]]
--> key
if_census -- false
--> while_loop
key
--> if_key_q{"if key is 'q'"} -- true
--> stop(("stop"))
if_key_q -- false
--> if_key_tab{"if key TAB"} -- true
--> increment_focus_index
--> get_window_size
if_key_tab -- false
--> get_window_size
--> set_vertical_limit
--> focus_navigation("logic by focus area\nSee flowchart below")
--> select_deselect_options("Select/deselect options\nSee flowchart below")
--> if_key_enter{"if key ENTER"} -- true
--> run_action[["run_action"]]
--> if_census_type{"if census type"} -- true
--> update_synced_states_counties
--> end_of_loop
if_census_type -- false
--> series_ids
--> sync_bls_ids[["get_synced_bls_series"]]
--> end_of_loop
end_of_loop
--> while_loop
flowchart TD
focus_nav(("Logic by Focus Area"))
--> if_focus_0_key_left_right{"if focus 0 (source selection)\nand key is left or right"} -- true
--> if_key_left{"if key LEFT"} -- true
--> decrease_source_sel
--> set_next_selections
if_key_left -- false
--> if_key_right{"if key RIGHT"} -- true
--> increse_source_sel
--> set_next_selections
if_key_right -- false
--> set_next_selections
--> source
--> if_type_census_again{"if type census"} -- true
--> sync_states[["get_synced_states if type is census"]]
--> end_focus(("end subroutine"))
if_type_census_again -- false
--> end_focus
if_focus_0_key_left_right -- false
--> if_focus_1_key_left_right{"if focus 1 and key left/right"} -- true
--> if_census_1{"if type census"} -- true
--> if_1_key_left{"if key LEFT"} -- true
--> decrease_scope
--> end_focus
if_focus_1_key_left_right -- false
--> if_focus_2_key_up_down{"if focus 2, key up/down"} -- false
--> if_focus_3_key_up_down{"if focus 3, key up/down"} -- false
--> if_focus_4_up_down{"if focus 4, key up/down"} -- false
--> end_focus
if_focus_2_key_up_down -- true
--> limit_3
--> if_2_key_up{"if key UP"} -- true
--> decrease_action
--> if_key_space_type_census
if_2_key_up -- false
--> if_2_key_down_less_limit{"if key DOWN and not last action"} -- true
--> increase_action
--> if_key_space_type_census
if_2_key_down_less_limit -- false
--> end_focus
if_focus_3_key_up_down -- true
--> if_census_3{"if census type"} -- true
--> if_3_key_up{"if key UP and state > 0"} -- true
--> decrease_state
--> if_state_less_scroll{"if state is less than scroll state"} -- true
--> decrease_state_scroll
--> end_focus
if_state_less_scroll -- false
--> end_focus
if_census_3 -- false
--> end_focus
if_3_key_up -- false
--> if_3_key_down{"if key DOWN and state not last"} -- true
--> increase_state
--> if_state_more_scroll{"if state is more than scroll + vertical limit"} -- true
--> increase_state_scroll
--> end_focus
if_state_more_scroll -- false
--> end_focus
if_census_3 -- false
--> if_bls_3{"if series_data exists"} -- false
--> end_focus
if_bls_3 -- true
--> if_3_bls_key_up{"if key UP and not first series"} -- true
--> decrease_series
--> if_less_bls_scroll{"if series less than scroll"} --true
--> decrease_bls_scroll
--> end_focus
if_less_bls_scroll -- false
--> end_focus
if_3_bls_key_up -- false
--> if_3_bls_key_down{"if key DOWN and not last series"} -- true
--> increase_series
--> if_more_than_window{"if more than scroll + vertical limit"} -- true
--> increase_bls_scroll
--> end_focus
if_more_than_window -- false
--> end_focus
if_3_bls_key_down -- false
--> end_focus
if_focus_4_up_down -- true
--> if_4_census{"if type census"} -- true
--> current_state_fips
--> county_limit
--> if_4_key_up{"if key UP and not first"} -- true
--> decrease_county
--> if_less_county_scroll{"if less than county scroll"} -- true
--> decrease_county_scroll
--> end_focus
if_less_county_scroll -- false
--> end_focus
if_4_key_up -- false
--> if_4_key_down{"if key DOWN and not last"} -- true
--> increase_county
--> if_bigger_scroll{"if beyond visible counties"} -- true
--> increase_county_scroll
--> end_focus
if_bigger_scroll -- false
--> end_focus
if_4_key_down -- false
--> end_focus
if_4_census -- false
--> if_4_key_up_detail{"if key UP and detail_scroll > 0"} -- true
--> decrease_detail_scroll
--> end_focus
if_4_key_up_detail -- false
--> if_4_key_down_detail{"if key DOWN and detail_scroll < 2"} -- true
--> increase_detail_scroll
--> end_focus
flowchart TD
selection(("Selection/deslection Options"))
--> if_key_space_type_census{"if SPACE key and type is census"} -- true
--> if_focus_3{"if focus 3"} -- true
--> state_fips
--> add_remove_state
--> end_selection(("end subroutine"))
if_focus_3 -- false
--> if_focus_4_county{"if focus 4"} -- true
--> current_state
--> counties_in_state
--> set_county_target
--> select_unselect_counties
--> end_selection
if_key_space_type_census -- false
--> if_key_aA_census{"if key a/A and census"} -- true
--> if_county{"if county level"} -- true
--> select_all_counties
--> end_selection
if_county -- false
--> if_state{"if state level"} -- true
--> select_all_states
--> end_selection
if_state -- false
--> end_selection
Data Validations
All raw data files are saved in the ./raw_data directory.
| Database |
Number of files |
Size |
acs5 |
7801 |
1.4 GB |
cbp |
104 |
1.1 GB |
ecnbasic |
104 |
336 MB |
ecn_napcs_prdind |
1 |
11 MB |
nes |
104 |
177 MB |
bls_cex |
5 |
492 MB |
bls_cpi |
1 |
317 MB |
bls_ppi |
1 |
355 MB |
| TOTAL |
|
> 4 GB |
Important issues that have come up and should be noted for future reference or work.
Currently the program does not record errors with BLS data. These errors (either margin of error or standard error) are not being downloaded. They exist, the current data does have a footnote if the error is really big (like > 25%). It's unclear if the error can be accessed with the API at this time (August 2026). The errors do exist in csv files (at least for CEX).