RAQ_streamlit_app / raq_extractor.py
bajajsg's picture
Upload raq_extractor.py
0602b3a verified
Raw
History Blame Contribute Delete
7.85 kB
"""
raq_extractor.py
----------------
Generic extractor for the RBI 'Report on Asset Quality' (RAQ) XBRL template.
The template has 25 sheets, each with a different table layout. Layouts are
described by IRIS/iFile markers (#LAYOUTSCSR#, #LAYOUTECSR#, #TABLE#, #CustPlc#,
#SERIAL#, #TYPDIM#) and the data rows are tagged in column B with an XBRL
element reference of the form `in-rbi-rep.xsd#in-rbi-rep_<Concept>`.
Rather than hard-coding 25 different parsers, we harvest every populated cell
into a single tidy "long" frame, attaching the best-effort row label (nearest
text to the left) and column header (nearest text above). This is robust to the
structural differences between sheets and is exactly the shape the data-quality
engine needs.
Public API
----------
extract_workbook(path) -> RAQExtract
.meta : dict (return code, bank, period, dates, version ...)
.long : DataFrame one row per populated data cell
.by_sheet : dict[str, DataFrame] convenience per-sheet pivots
.sheets : list[str] data sheets found
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from datetime import datetime
import openpyxl
import pandas as pd
ELEMENT_PREFIX = "in-rbi-rep.xsd#"
MARKERS = {
"#LAYOUTSCSR#", "#LAYOUTECSR#", "#LAYOUTSCER#", "#LAYOUTECER#",
"#TABLE#", "#CustPlc#", "#SERIAL#", "#TYPDIM#", "#LAYOUTSCSR#",
}
# sheets that are config / taxonomy plumbing, not reportable data
NON_DATA_SHEETS = {
"StartUpDataSheet", "MainSheet", "Navigation", "StartUp",
"Data", "+FootnoteTexts", "+Elements", "+Lineitems",
}
def _is_marker(v) -> bool:
return isinstance(v, str) and v.strip() in MARKERS
def _is_element(v) -> bool:
return isinstance(v, str) and v.startswith(ELEMENT_PREFIX)
def _is_text(v) -> bool:
return isinstance(v, str) and v.strip() != "" and not _is_marker(v) and not _is_element(v)
def _clean_label(v: str) -> str:
s = re.sub(r"\s+", " ", str(v)).strip()
return s
def _concept_from_element(v: str) -> str:
# in-rbi-rep.xsd#in-rbi-rep_AssetsCurrentTermLoans -> AssetsCurrentTermLoans
tail = v.split("#")[-1]
return tail.split("in-rbi-rep_")[-1] if "in-rbi-rep_" in tail else tail
@dataclass
class RAQExtract:
meta: dict = field(default_factory=dict)
long: pd.DataFrame = field(default_factory=pd.DataFrame)
by_sheet: dict = field(default_factory=dict)
sheets: list = field(default_factory=list)
def _extract_meta(wb) -> dict:
"""Pull return-level metadata from the General Information sheet."""
meta = {}
if "General Information" not in wb.sheetnames:
return meta
ws = wb["General Information"]
for row in ws.iter_rows(values_only=True):
cells = [c for c in row if c is not None]
# rows look like: <element/key> | <Label> | <Value>
if len(cells) >= 2:
key = _clean_label(cells[-2]) if isinstance(cells[-2], str) else None
val = cells[-1]
if key and isinstance(key, str):
low = key.lower()
if low in (
"return name", "return code", "reporting institution",
"bank code", "for the period ended", "reporting frequency",
"date of report", "status", "validation status",
"bank category", "return version", "start date",
):
meta[key] = val
return meta
def _header_for_column(header_rows, col_idx) -> str:
"""Join all header-row texts found at this column (top-to-bottom)."""
parts = []
for hr in header_rows:
v = hr.get(col_idx)
if v and v not in parts:
parts.append(v)
return " | ".join(parts)
def _extract_sheet(ws) -> pd.DataFrame:
"""Harvest every populated data cell on a sheet into tidy rows."""
records = []
header_rows = [] # list of {col_idx: text} captured since last #TABLE# open
current_row_label = None # last text label seen at left of a data block
table_open = False
table_id = None
rows = list(ws.iter_rows())
for ri, row in enumerate(rows, start=1):
values = [c.value for c in row]
texts = {ci: _clean_label(v) for ci, v in enumerate(values, 1) if _is_text(v)}
has_marker_table = any(isinstance(v, str) and v.strip() == "#TABLE#" for v in values)
has_element = any(_is_element(v) for v in values)
# capture a GUID block id (table identity) -> first cell that looks like a guid
for v in values:
if isinstance(v, str) and re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{4}-.*", v.strip()):
table_id = v.strip()
if has_marker_table:
table_open = not table_open
if table_open:
header_rows = [] # reset header context at the start of a data block
continue
# Header-ish row: multiple texts, no element ref -> treat as column headers
if not has_element and len(texts) >= 2 and not table_open:
header_rows.append(texts)
continue
if not has_element and len(texts) >= 2 and table_open:
header_rows.append(texts)
continue
if has_element:
# row label = left-most text cell on this row (cols C/D), else carry last
label = None
for ci in sorted(texts):
if ci >= 3: # labels live from column C onward
label = texts[ci]
break
if label:
current_row_label = label
element_ref = next((v for v in values if _is_element(v)), None)
concept = _concept_from_element(element_ref) if element_ref else None
# numeric / value cells
for ci, v in enumerate(values, 1):
if isinstance(v, bool):
continue
is_num = isinstance(v, (int, float))
is_val_text = isinstance(v, str) and _is_text(v) and ci >= 4 and texts.get(ci) != current_row_label
if is_num or is_val_text:
records.append({
"row_label": current_row_label,
"concept": concept,
"col_idx": ci,
"col_header": _header_for_column(header_rows, ci),
"value": v,
"is_numeric": bool(is_num),
"cell": f"{openpyxl.utils.get_column_letter(ci)}{ri}",
"table_id": table_id,
})
else:
# single stray text -> may be a running row label for following block
if len(texts) == 1:
ci = next(iter(texts))
if ci >= 3:
current_row_label = texts[ci]
return pd.DataFrame.from_records(records)
def extract_workbook(path: str) -> RAQExtract:
wb = openpyxl.load_workbook(path, data_only=True, read_only=False)
meta = _extract_meta(wb)
frames = []
by_sheet = {}
data_sheets = []
for name in wb.sheetnames:
if name in NON_DATA_SHEETS:
continue
ws = wb[name]
df = _extract_sheet(ws)
if df.empty:
continue
df.insert(0, "sheet", name)
frames.append(df)
by_sheet[name] = df
data_sheets.append(name)
long = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()
return RAQExtract(meta=meta, long=long, by_sheet=by_sheet, sheets=data_sheets)
if __name__ == "__main__":
import sys
p = sys.argv[1] if len(sys.argv) > 1 else "RAQ.XLSX"
ex = extract_workbook(p)
print("META:", ex.meta)
print("DATA SHEETS:", len(ex.sheets))
print("TOTAL DATA CELLS:", len(ex.long))
print(ex.long.head(20).to_string())