""" COLUMN MAPPER Uses Gemini Flash to automatically map dataset columns to standardized internal variable names. """ import json import pandas as pd from google import genai from google.genai import types # Standard variables the pipeline needs REQUIRED_VARIABLES = { "SUBJECT_ID": "Unique patient/subject identifier", "TREATMENT_START": "Date when treatment started (first dose date)", "TREATMENT_END": "Date when treatment ended (end of study treatment date)", "RESPONSE_DATE": "Date of overall response assessment", "RESPONSE_VALUE": "Overall response value (CR/PR/SD/PD or numeric equivalent)", "BASELINE_SUM": "Sum of target lesion diameters at baseline", "BASELINE_DATE": "Date of baseline tumor measurement", "FOLLOWUP_SUM": "Sum of target lesion diameters at follow-up visits", "FOLLOWUP_DATE": "Date of follow-up tumor measurement", "END_REASON": "Reason for end of study treatment (death, withdrawal, etc.)", "PRIOR_TREATMENTS": "Prior treatment/medication terms", "MEDICAL_HISTORY": "Medical history terms (for metastasis detection)", "LESION_LOCATION": "Location of tumor lesions (target or non-target)", } def build_prompt(tables_summary: str) -> str: return f"""You are an expert in clinical trial data standards (CDISC/SDTM). I have a clinical trial dataset with the following tables and columns: {tables_summary} Your task: Map each of the following REQUIRED VARIABLES to the most likely table name and column name from the dataset above. REQUIRED VARIABLES: {json.dumps(REQUIRED_VARIABLES, indent=2)} Rules: - For each variable, return the best matching TABLE and COLUMN from the dataset. - If a variable maps to multiple tables/columns (e.g. lesion location appears in 2 tables), return all matches as a list. - If no match found, set to null. - Return ONLY valid JSON, no explanation, no markdown. Return format: {{ "SUBJECT_ID": {{"table": "DM", "column": "USUBJID"}}, "TREATMENT_START": {{"table": "EX", "column": "EXSTDTC"}}, "RESPONSE_DATE": {{"table": "RS", "column": "RSDTC"}}, "RESPONSE_VALUE": {{"table": "RS", "column": "RSSTRESC"}}, "BASELINE_SUM": {{"table": "TR", "column": "TRSTRESN"}}, "LESION_LOCATION": [{{"table": "TR", "column": "TRLOC"}}, {{"table": "TU", "column": "TULOC"}}], ... }} """ def summarize_tables(dataframes: dict, sample_rows: int = 3) -> str: """Build a compact summary of all tables: columns + sample values.""" lines = [] for name, df in dataframes.items(): lines.append(f"\nTABLE: {name}") lines.append(f" Rows: {len(df)}, Columns: {list(df.columns)}") if len(df) > 0: sample = df.head(sample_rows).to_dict(orient='records') lines.append(f" Sample rows: {json.dumps(sample, default=str)[:800]}") return "\n".join(lines) def map_columns(dataframes: dict, api_key: str) -> dict: """ Main entry point. Sends table summaries to Gemini and returns column mapping dict. """ client = genai.Client(api_key=api_key) tables_summary = summarize_tables(dataframes) prompt = build_prompt(tables_summary) print("Sending to Gemini for column mapping...") response = client.models.generate_content( model="gemini-1.5-flash", contents=prompt, config=types.GenerateContentConfig( temperature=0.0, ), ) raw = response.text.strip() # Clean up if Gemini wraps in markdown fences if raw.startswith("```"): parts = raw.split("```") raw = parts[1] if len(parts) > 1 else raw if raw.startswith("json"): raw = raw[4:] raw = raw.strip() try: mapping = json.loads(raw) print(f"Column mapping complete: {len(mapping)} variables mapped") return mapping except json.JSONDecodeError as e: raise ValueError(f"Gemini returned invalid JSON: {e}\nRaw response:\n{raw}") def get_value(dataframes: dict, mapping: dict, variable: str, subject_id=None, subject_col: str = None) -> pd.DataFrame | None: """ Helper: retrieve data for a mapped variable, optionally filtered by subject. Returns a DataFrame or None. """ entry = mapping.get(variable) if entry is None: return None # Handle list of mappings entries = entry if isinstance(entry, list) else [entry] results = [] for e in entries: table = e.get("table") column = e.get("column") if table not in dataframes or column not in dataframes[table].columns: continue df = dataframes[table][[column]].copy() df.columns = [variable] df["_source_table"] = table if subject_id is not None and subject_col: if subject_col in dataframes[table].columns: mask = dataframes[table][subject_col] == subject_id df = df[mask.values] results.append(df) if not results: return None return pd.concat(results, ignore_index=True)