File size: 7,381 Bytes
eb85c59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# core/variable_loader.py
import os
import glob
import json
import time
import logging

logger = logging.getLogger(__name__)

try:
    import pandas as pd
except Exception:
    pd = None

# cache path (temporary)
CACHE_PATH = "/tmp/ct_var_cache.json"
CACHE_TTL_SECONDS = 60 * 60  # 1 hour; adjust as needed

# candidate filenames / patterns to detect relevant excel files
DEFAULT_PATTERNS = [
    "*SDTM*.xls*", "*SDTMIG*.xls*", "*SDTM_*.xls*", "SDTM*.xls*",
    "*ADaM*.xls*", "*ADaMIG*.xls*", "ADaM*.xls*",
    "*CDASH*.xls*", "*CDASHIG*.xls*", "CDASH*.xls*"
]

# Typical column name candidates
VAR_COL_CANDIDATES = [
    "variable", "variable name", "varname", "var", "column", "fieldname"
]
LABEL_COL_CANDIDATES = [
    "label", "variable label", "var label", "column label"
]
DESC_COL_CANDIDATES = [
    "description", "definition", "long name", "comments", "notes"
]
ROLE_COL_CANDIDATES = [
    "role", "type", "datatype", "origin"
]


def _first_existing(columns, candidates):
    if not columns:
        return None
    low = {c.strip().lower(): c for c in columns}
    for cand in candidates:
        for k, orig in low.items():
            if cand == k or cand in k:
                return orig
    return None


def _discover_files(search_paths=None, patterns=None):
    patterns = patterns or DEFAULT_PATTERNS
    search_paths = search_paths or [
        ".", "/workspace/data", "/mnt/data", os.getcwd(),
        "/root/.cache/huggingface/hub", "/home/user/.cache/huggingface/hub",
        "/root/.cache/huggingface/hub/datasets--essprasad--CT-Chat-Docs",
        "/home/user/.cache/huggingface/hub/datasets--essprasad--CT-Chat-Docs",
    ]
    found = []
    for base in search_paths:
        if not base or not os.path.exists(base):
            continue
        for pat in patterns:
            try:
                matches = glob.glob(os.path.join(base, pat), recursive=True)
                for m in matches:
                    if os.path.isfile(m) and m.lower().endswith((".xls", ".xlsx")):
                        found.append(os.path.abspath(m))
            except Exception:
                continue
    # dedupe but keep order
    seen = set()
    unique = []
    for p in found:
        if p not in seen:
            seen.add(p)
            unique.append(p)
    return unique


def _extract_from_df(df, filename):
    """
    Given a dataframe, find likely variable/label/description columns and extract rows.
    Returns list of dicts.
    """
    out = []
    if df is None or df.shape[0] == 0:
        return out

    cols = list(df.columns)
    term_col = _first_existing(cols, VAR_COL_CANDIDATES)
    label_col = _first_existing(cols, LABEL_COL_CANDIDATES)
    desc_col = _first_existing(cols, DESC_COL_CANDIDATES)
    role_col = _first_existing(cols, ROLE_COL_CANDIDATES)

    # If we absolutely cannot find a term column, try first column
    if not term_col:
        term_col = cols[0] if cols else None

    # If there's absolutely no useful columns, give up
    if not term_col:
        return out

    for _, row in df.iterrows():
        try:
            term = str(row.get(term_col, "") or "").strip()
        except Exception:
            term = ""
        if not term:
            continue

        label = ""
        desc = ""
        role = ""
        try:
            label = str(row.get(label_col, "") or "").strip() if label_col in df.columns else ""
        except Exception:
            label = ""
        try:
            desc = str(row.get(desc_col, "") or "").strip() if desc_col in df.columns else ""
        except Exception:
            desc = ""
        try:
            role = str(row.get(role_col, "") or "").strip() if role_col in df.columns else ""
        except Exception:
            role = ""

        # Compose a clean definition
        parts = []
        if label:
            parts.append(f"Label: {label}")
        if desc:
            parts.append(f"Description: {desc}")
        if role:
            parts.append(f"Role/Origin: {role}")
        definition = "  \n".join(parts).strip() or (label or desc or "")

        out.append({
            "term": term,
            "definition": definition,
            "file": os.path.basename(filename),
            "type": "variable",
            "sources": [os.path.basename(filename)]
        })

    return out


def load_variable_metadata(search_paths=None, use_cache=True, verbose=True):
    """
    Discover SDTM/ADaM/CDASH excel files and extract variable metadata.
    Returns list of dicts: {'term','definition','file','type','sources'}
    """

    # quick fail if pandas not installed
    if pd is None:
        logger.warning("pandas not available — variable metadata loading skipped.")
        return []

    # cache handling
    try:
        if use_cache and os.path.exists(CACHE_PATH):
            mtime = os.path.getmtime(CACHE_PATH)
            if time.time() - mtime < CACHE_TTL_SECONDS:
                if verbose:
                    logger.info("Loading variable metadata from cache: %s", CACHE_PATH)
                with open(CACHE_PATH, "r", encoding="utf-8") as f:
                    return json.load(f)
    except Exception:
        # continue if cache read fails
        pass

    files = _discover_files(search_paths=search_paths)
    if verbose:
        logger.info("Variable loader discovered %d candidate Excel files.", len(files))

    all_entries = []
    for fx in files:
        try:
            # read all sheets (ExcelFile faster for many sheets)
            xls = pd.ExcelFile(fx)
            # iterate sheets:
            for sheet in xls.sheet_names:
                try:
                    df = pd.read_excel(fx, sheet_name=sheet)
                    # drop rows where all cells are NaN
                    df = df.dropna(how="all")
                    entries = _extract_from_df(df, fx)
                    if entries:
                        # annotate with sheet name to improve provenance
                        for e in entries:
                            e["sources"].append(f"{os.path.basename(fx)}::{sheet}")
                        all_entries.extend(entries)
                except Exception:
                    # try next sheet
                    continue
        except Exception:
            # fallback: try single-sheet read
            try:
                df = pd.read_excel(fx)
                df = df.dropna(how="all")
                entries = _extract_from_df(df, fx)
                all_entries.extend(entries)
            except Exception as e:
                logger.debug("Failed reading excel %s: %s", fx, e)
                continue

    # dedupe by term (keep first occurrence)
    seen = {}
    deduped = []
    for e in all_entries:
        key = (e["term"].strip().lower())
        if key and key not in seen:
            seen[key] = True
            deduped.append(e)

    # write cache
    try:
        with open(CACHE_PATH, "w", encoding="utf-8") as f:
            json.dump(deduped, f, ensure_ascii=False, indent=2)
    except Exception:
        pass

    if verbose:
        logger.info("Variable loader extracted %d unique variables.", len(deduped))

    return deduped


if __name__ == "__main__":
    # quick CLI for debugging
    items = load_variable_metadata(verbose=True)
    print(f"[variable_loader] extracted {len(items)} items")
    if items:
        print("Sample:", items[:5])