{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceType":"competition","sourceId":10338,"databundleVersionId":862042,"isSourceIdPinned":false},{"sourceType":"datasetVersion","sourceId":1299795,"datasetId":751906,"databundleVersionId":1331968}],"dockerImageVersionId":31400,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport pydicom\n\n# 1. Dynamically search for the correct folder path\nbase_input_dir = '/kaggle/input'\nauthentic_dir = None\n\nfor root, dirs, files in os.walk(base_input_dir):\n    if 'stage_2_train_images' in root:\n        authentic_dir = root\n        break\n\n# 2. Check if we found it and read the files\nif authentic_dir:\n    # Get only .dcm files\n    dcm_files = [f for f in os.listdir(authentic_dir) if f.endswith('.dcm')]\n    print(f\"✅ Success! Found directory at: {authentic_dir}\")\n    print(f\"✅ Found {len(dcm_files)} authentic DICOMs.\")\n    \n    # Read the first file to test pydicom\n    if dcm_files:\n        sample_path = os.path.join(authentic_dir, dcm_files[0])\n        sample = pydicom.dcmread(sample_path)\n        print(\"\\n--- TEST READING ---\")\n        print(f\"File: {dcm_files[0]}\")\n        print(\"Manufacturer:\", sample.get((0x0008, 0x0070), \"None (Tag missing or empty)\"))\nelse:\n    print(\"❌ Could not find the folder. Ensure the RSNA dataset is attached in the right-hand 'Input' pane.\")","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-05-30T06:45:15.882816Z","iopub.execute_input":"2026-05-30T06:45:15.883084Z","iopub.status.idle":"2026-05-30T06:46:05.446388Z","shell.execute_reply.started":"2026-05-30T06:45:15.883049Z","shell.execute_reply":"2026-05-30T06:46:05.445607Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install cryptography","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-30T06:48:22.268889Z","iopub.execute_input":"2026-05-30T06:48:22.269228Z","iopub.status.idle":"2026-05-30T06:48:27.712177Z","shell.execute_reply.started":"2026-05-30T06:48:22.269198Z","shell.execute_reply":"2026-05-30T06:48:27.711088Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!pip install pydicom cryptography numpy\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-30T07:04:18.940226Z","iopub.execute_input":"2026-05-30T07:04:18.941093Z","iopub.status.idle":"2026-05-30T07:04:22.930237Z","shell.execute_reply.started":"2026-05-30T07:04:18.941043Z","shell.execute_reply":"2026-05-30T07:04:22.928825Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pydicom\nfrom pydicom.dataset import Dataset, FileMetaDataset\nfrom pydicom.uid import ExplicitVRLittleEndian, SecondaryCaptureImageStorage\nfrom cryptography.hazmat.primitives.asymmetric import rsa, padding\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.exceptions import InvalidSignature\n\n# =====================================================================\n# 1. INITIALIZATION & CRYPTOGRAPHIC SETUP\n# =====================================================================\nprint(\"[-] Initializing Security Infrastructure...\")\n\n# Generate simulated RSA-2048 keys for the Trusted Hospital Scanner\nscanner_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)\nscanner_public_key = scanner_private_key.public_key()\n\n# Generate keys for an outside attacker/rogue actor\nattacker_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)\n\n# Trust Registry (Simulating Network Infrastructure white-listing Authorized Keys)\ntrusted_registry = {\n    \"SCANNER_MODALITY_01\": scanner_public_key\n}\n\n# Define clinical statistical boundaries for validation\nVALID_PIXEL_SPACING_MIN = 0.14\nVALID_PIXEL_SPACING_MAX = 0.22\n\n\n# =====================================================================\n# 2. FILE CREATION ENGINE (Simulating Raw Scanner Output)\n# =====================================================================\ndef create_base_dicom(pixel_spacing=0.18, rows=512, cols=512):\n    \"\"\"Generates a standard-compliant, clean synthetic medical DICOM file.\"\"\"\n    file_meta = FileMetaDataset()\n    file_meta.TransferSyntaxUID = ExplicitVRLittleEndian\n    file_meta.MediaStorageSOPClassUID = SecondaryCaptureImageStorage\n    file_meta.MediaStorageSOPInstanceUID = pydicom.uid.generate_uid()\n    file_meta.ImplementationClassUID = pydicom.uid.generate_uid()\n\n    ds = Dataset()\n    ds.file_meta = file_meta\n    ds.is_little_endian = True\n    ds.is_implicit_VR = False\n\n    # Mandatory Meta Tags\n    ds.SOPClassUID = SecondaryCaptureImageStorage\n    ds.SOPInstanceUID = file_meta.MediaStorageSOPInstanceUID\n    ds.PatientID = \"PT-99482\"\n    ds.Modality = \"CR\"\n    \n    # Dimensions & Bit Allocations\n    ds.Rows = rows\n    ds.Columns = cols\n    ds.BitsAllocated = 16\n    ds.BitsStored = 12\n    ds.HighBit = 11\n    ds.PixelRepresentation = 0\n    \n    # Clinical Metadata Tag\n    ds.PixelSpacing = [str(pixel_spacing), str(pixel_spacing)]\n    \n    # Generate mock lung field pixel data (16-bit array)\n    pixels = np.ones((rows, cols), dtype=np.uint16) * 200\n    ds.PixelData = pixels.tobytes()\n    \n    return ds\n\n\n# =====================================================================\n# 3. HYBRID SECURITY GATEWAY INSPECTION ENGINE\n# =====================================================================\ndef hybrid_security_gateway(ds, signature_bytes=None, sender_id=None):\n    \"\"\"\n    Inspects an incoming DICOM file using three distinct layers of security.\n    No Computer Vision models or pixel manipulation libraries are used.\n    \"\"\"\n    print(f\"\\n[Gateway Intercept] Inspecting incoming file from sender: '{sender_id}'...\")\n    \n    # -----------------------------------------------------------------\n    # TIER 1: CRYPTOGRAPHIC FIREWALL (Network Security & Hashing)\n    # -----------------------------------------------------------------\n    print(\" -> Tier 1: Checking Cryptographic Pipeline...\")\n    if signature_bytes is None or sender_id not in trusted_registry:\n        print(\"    [!] WARNING: Cryptographic Signature is missing or untrusted. Routing to Forensic Tiers...\")\n        crypto_passed = False\n    else:\n        pub_key = trusted_registry[sender_id]\n        raw_pixel_bytes = ds.PixelData\n        \n        try:\n            # Re-hash the pixel matrix bytes and cross-examine with the signature\n            pub_key.verify(\n                signature_bytes,\n                raw_pixel_bytes,\n                padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),\n                hashes.SHA256()\n            )\n            print(\"    [PASSED] Cryptographic verification successful. Integrity 100% Guaranteed.\")\n            print(\"    [DECISION] ACCEPTED TO PACS NETWORK\")\n            return True\n        except InvalidSignature:\n            print(\"    [CRITICAL FAILURE] Signature verification failed! The pixel matrix has been modified.\")\n            print(\"    [DECISION] REJECTED: MALICIOUS PACKET TAMPERING DETECTED\")\n            return False\n\n    # -----------------------------------------------------------------\n    # TIER 2: STRUCTURAL INTEGRITY CHECK (Deterministic Parsing)\n    # -----------------------------------------------------------------\n    print(\" -> Tier 2: Running Structural Integrity Parser...\")\n    try:\n        expected_byte_length = int(ds.Rows * ds.Columns * (ds.BitsAllocated / 8))\n        actual_byte_length = len(ds.PixelData)\n        \n        if expected_byte_length != actual_byte_length:\n            print(f\"    [STRUCTURAL FAILURE] Header Math Contradiction!\")\n            print(f\"    Expected: {expected_byte_length} bytes based on Rows/Cols, Found: {actual_byte_length} bytes.\")\n            print(\"    [DECISION] REJECTED: INVALID REWRITTEN FILE WRAPPER (GAN ARTIFACT)\")\n            return False\n        print(\"    [PASSED] Byte stream dimensions perfectly match structural header parameters.\")\n    except Exception as e:\n        print(f\"    [STRUCTURAL FAILURE] Missing essential tags for geometric computation: {str(e)}\")\n        return False\n\n    # -----------------------------------------------------------------\n    # TIER 3: METADATA STATISTICAL ANOMALY DETECTION (Distribution Bounds)\n    # -----------------------------------------------------------------\n    print(\" -> Tier 3: Evaluating Metadata Distributions...\")\n    if 'PixelSpacing' in ds:\n        try:\n            spacing_val = float(ds.PixelSpacing[0])\n            if not (VALID_PIXEL_SPACING_MIN <= spacing_val <= VALID_PIXEL_SPACING_MAX):\n                print(f\"    [ANOMALY FAILURE] Statistical Outlier Spotted!\")\n                print(f\"    Pixel Spacing is set to {spacing_val} mm. Standard clinical CR range is {VALID_PIXEL_SPACING_MIN}-{VALID_PIXEL_SPACING_MAX} mm.\")\n                print(\"    [DECISION] REJECTED: SYNTHETIC METADATA PROFILE DETECTED\")\n                return False\n            print(f\"    [PASSED] Metadata tag metrics ({spacing_val} mm) match expected clinical distributions.\")\n        except ValueError:\n            print(\"    [ANOMALY FAILURE] Pixel Spacing tag contains corrupt data formats.\")\n            return False\n    else:\n        print(\"    [ANOMALY FAILURE] Essential clinical modality tags missing entirely from dataset payload.\")\n        return False\n\n    print(\"    [PASSED] Unsigned file passed all structural and statistical forensic hurdles safely.\")\n    print(\"    [DECISION] ACCEPTED WITH FORENSIC AUDIT LOG ENTRY\")\n    return True\n\n\n# =====================================================================\n# 4. LIVE EXPERIMENT SIMULATION SCENARIOS\n# =====================================================================\nif __name__ == \"__main__\":\n    \n    # --- SCENARIO A: Standard Authorized Pipeline Transfer (Authentic) ---\n    print(\"\\n\" + \"=\"*70 + \"\\nSCENARIO A: Clean Data Pipeline inside Authorized Hospital Network\\n\" + \"=\"*70)\n    ds_authentic = create_base_dicom()\n    \n    # Scanner signs the raw byte array of pixels using the private key\n    pixel_payload = ds_authentic.PixelData\n    valid_signature = scanner_private_key.sign(\n        pixel_payload,\n        padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),\n        hashes.SHA256()\n    )\n    # File passes into the gateway\n    hybrid_security_gateway(ds_authentic, signature_bytes=valid_signature, sender_id=\"SCANNER_MODALITY_01\")\n\n\n    # --- SCENARIO B: Man-In-The-Middle Deepfake Attack (Pixel Tampering) ---\n    print(\"\\n\" + \"=\"*70 + \"\\nSCENARIO B: Malicious Actor Injects Fake Lesions Into Signed Image\\n\" + \"=\"*70)\n    ds_tampered = create_base_dicom()\n    \n    # Attacker alters the raw bytes of the pixel matrix to generate a fake clinical condition\n    modified_pixels = np.frombuffer(ds_tampered.PixelData, dtype=np.uint16).copy()\n    modified_pixels[5000:6000] += 400  # Tampering with raw sequence data\n    ds_tampered.PixelData = modified_pixels.tobytes()\n    \n    # Attacker forwards the file using the original collected signature to look legitimate\n    hybrid_security_gateway(ds_tampered, signature_bytes=valid_signature, sender_id=\"SCANNER_MODALITY_01\")\n\n\n    # --- SCENARIO C: Rogue AI Generation (Structural Wrap Failure) ---\n    print(\"\\n\" + \"=\"*70 + \"\\nSCENARIO C: Unsigned Deepfake DICOM Generated From External GAN Wrapper\\n\" + \"=\"*70)\n    # Simulates an AI script mapping a generated matrix into a DICOM framework improperly\n    ds_gan_structural = create_base_dicom(rows=512, cols=512)\n    # The script mistakenly dumps a 256x256 byte payload, creating a physical matrix size mismatch\n    corrupted_gan_pixels = np.ones((256, 256), dtype=np.uint16).tobytes()\n    ds_gan_structural.PixelData = corrupted_gan_pixels\n    \n    # Passes without a cryptographic signature profile\n    hybrid_security_gateway(ds_gan_structural, signature_bytes=None, sender_id=\"UNKNOWN_EXTERNAL_SOURCE\")\n\n\n    # --- SCENARIO D: Sophisticated AI Generation (Statistical Outlier) ---\n    print(\"\\n\" + \"=\"*70 + \"\\nSCENARIO D: AI Script Correctly Wraps Dimensions But Generates Invalid Metadata\\n\" + \"=\"*70)\n    # GAN tool produces perfectly aligned pixel arrays but fills tags with default web engine presets (1.0 mm)\n    ds_gan_statistical = create_base_dicom(pixel_spacing=1.0)\n    \n    # Passes without a signature profile\n    hybrid_security_gateway(ds_gan_statistical, signature_bytes=None, sender_id=\"UNKNOWN_EXTERNAL_SOURCE\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-30T07:04:34.523148Z","iopub.execute_input":"2026-05-30T07:04:34.523960Z","iopub.status.idle":"2026-05-30T07:04:34.862383Z","shell.execute_reply.started":"2026-05-30T07:04:34.523921Z","shell.execute_reply":"2026-05-30T07:04:34.861618Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pydicom\nfrom cryptography.hazmat.primitives.asymmetric import rsa, padding\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.exceptions import InvalidSignature\n\n# =====================================================================\n# 1. GATEWAY CONFIGURATION & KEYS DETONATION\n# =====================================================================\nprint(\"[*] Initializing Zero-Trust Security Infrastructure...\")\n\n# Generate keys for our trusted institutional scanner\nhospital_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)\nhospital_public_key = hospital_private_key.public_key()\n\ntrusted_registry = {\n    \"TRUSTED_RSNA_SCANNER_01\": hospital_public_key\n}\n\n# Define real clinical baseline ranges for Chest Radiographs (CR)\nVALID_PIXEL_SPACING_MIN = 0.11\nVALID_PIXEL_SPACING_MAX = 0.22\n\n# Locate the verified dataset directory\nbase_input_dir = '/kaggle/input/competitions/rsna-pneumonia-detection-challenge/stage_2_train_images'\ndcm_files = [f for f in os.listdir(base_input_dir) if f.endswith('.dcm')]\n\nprint(f\"[+] Successfully hooked to dataset. Processing real target files...\\n\")\n\n\n# =====================================================================\n# 2. THE COMPREHENSIVE HYBRID SECURITY GATEWAY\n# =====================================================================\ndef hybrid_security_gateway(ds, signature_bytes=None, sender_id=None):\n    \"\"\"\n    Evaluates a real RSNA DICOM dataset packet using multi-tier \n    non-Computer Vision integrity checks.\n    \"\"\"\n    # -----------------------------------------------------------------\n    # TIER 1: CRYPTOGRAPHIC FIREWALL\n    # -----------------------------------------------------------------\n    if signature_bytes is not None and sender_id in trusted_registry:\n        pub_key = trusted_registry[sender_id]\n        try:\n            pub_key.verify(\n                signature_bytes,\n                ds.PixelData,\n                padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),\n                hashes.SHA256()\n            )\n            return \"PASSED (Cryptographic Trust)\"\n        except InvalidSignature:\n            return \"REJECTED (Malicious Modification / Hash Mismatch)\"\n\n    # -----------------------------------------------------------------\n    # TIER 2: STRUCTURAL INTEGRITY PARSER\n    # -----------------------------------------------------------------\n    try:\n        rows = ds.Rows\n        cols = ds.Columns\n        bits_allocated = ds.BitsAllocated\n        expected_byte_length = int(rows * cols * (bits_allocated / 8))\n        actual_byte_length = len(ds.PixelData)\n        \n        if expected_byte_length != actual_byte_length:\n            return f\"REJECTED (Structural Violation: Expected {expected_byte_length}B, Found {actual_byte_length}B)\"\n    except AttributeError as visually_flag:\n        return \"REJECTED (Structural Violation: Missing fundamental geometry tags)\"\n\n    # -----------------------------------------------------------------\n    # TIER 3: METADATA STATISTICAL ANOMALY ENGINE\n    # -----------------------------------------------------------------\n    if 'PixelSpacing' in ds:\n        try:\n            spacing_val = float(ds.PixelSpacing[0])\n            if not (VALID_PIXEL_SPACING_MIN <= spacing_val <= VALID_PIXEL_SPACING_MAX):\n                return f\"REJECTED (Statistical Anomaly: Outlier PixelSpacing {spacing_val}mm)\"\n        except (ValueError, TypeError):\n            return \"REJECTED (Statistical Anomaly: Corrupted metadata format)\"\n    else:\n        # If the tag was completely stripped by anonymization scripts, flag it as a risk point\n        return \"REJECTED (Forensic Risk: Missing Clinical Modality Footprint)\"\n\n    return \"PASSED (Forensic Clearance: Structural & Statistical Soundness)\"\n\n\n# =====================================================================\n# 3. BATCH EXECUTION MATRIX\n# =====================================================================\n# Process a sample slice of 20 files to evaluate performance behaviors\nbatch_target_size = 20\n\nprint(f\"{'Filename':<40} | {'Simulated Condition':<25} | {'Gateway Decision'}\")\nprint(\"-\" * 100)\n\nfor i in range(min(batch_target_size, len(dcm_files))):\n    file_name = dcm_files[i]\n    file_path = os.path.join(base_input_dir, file_name)\n    \n    # Read the authentic RSNA file\n    ds = pydicom.dcmread(file_path)\n    \n    # Split the batch into different structural scenarios\n    if i < 5:\n        # Scenario 1: Clean clinical pipeline. Scanner signs the image.\n        signature = hospital_private_key.sign(\n            ds.PixelData,\n            padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),\n            hashes.SHA256()\n        )\n        decision = hybrid_security_gateway(ds, signature_bytes=signature, sender_id=\"TRUSTED_RSNA_SCANNER_01\")\n        condition = \"Authentic Signed Pipeline\"\n        \n    elif i < 10:\n        # Scenario 2: Deepfake attack. Image was signed, but attacker modifies pixels.\n        signature = hospital_private_key.sign(\n            ds.PixelData,\n            padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),\n            hashes.SHA256()\n        )\n        # Modify pixel block array directly to simulate injected medical deepfake\n        pixel_array = ds.pixel_array.copy()\n        pixel_array[200:300, 200:300] = 0  # Blacking out an area\n        ds.PixelData = pixel_array.tobytes()\n        \n        decision = hybrid_security_gateway(ds, signature_bytes=signature, sender_id=\"TRUSTED_RSNA_SCANNER_01\")\n        condition = \"Tampered Signed Image\"\n        \n    elif i < 15:\n        # Scenario 3: Unsigned file with broken structural geometry (GAN wrapper bug)\n        pixel_array = ds.pixel_array.copy()\n        # Crop the payload byte array down without rewriting the header tag boundaries\n        cropped_pixels = pixel_array[0:512, 0:512].tobytes()\n        ds.PixelData = cropped_pixels\n        \n        decision = hybrid_security_gateway(ds, signature_bytes=None, sender_id=\"UNVERIFIED_EXTERNAL\")\n        condition = \"GAN Structural Mismatch\"\n        \n    else:\n        # Scenario 4: Unsigned external file with anomalous metadata configurations\n        ds.PixelSpacing = [\"1.5\", \"1.5\"]  # Artificial value far out of human anatomical bounds\n        decision = hybrid_security_gateway(ds, signature_bytes=None, sender_id=\"UNVERIFIED_EXTERNAL\")\n        condition = \"GAN Metadata Outlier\"\n\n    print(f\"{file_name:<40} | {condition:<25} | {decision}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-30T07:08:54.593454Z","iopub.execute_input":"2026-05-30T07:08:54.594140Z","iopub.status.idle":"2026-05-30T07:08:55.133193Z","shell.execute_reply.started":"2026-05-30T07:08:54.594109Z","shell.execute_reply":"2026-05-30T07:08:55.132469Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pydicom\nimport numpy as np\nimport cv2 \nimport shutil\n\n# --- 1. Setup Directories ---\nbase_input_dir = '/kaggle/input/competitions/rsna-pneumonia-detection-challenge/stage_2_train_images'\nworking_dir = '/kaggle/working'\nauth_dir = os.path.join(working_dir, 'dataset/authentic')\nmani_dir = os.path.join(working_dir, 'dataset/manipulated')\n\nos.makedirs(auth_dir, exist_ok=True)\nos.makedirs(mani_dir, exist_ok=True)\n\n# --- 2. Get a Sample of 500 Files ---\nall_files = [f for f in os.listdir(base_input_dir) if f.endswith('.dcm')]\nsample_files = all_files[:2000] \n\nprint(f\"Generating dataset of {len(sample_files)} images... This will take a moment.\")\n\nfor idx, filename in enumerate(sample_files):\n    source_path = os.path.join(base_input_dir, filename)\n    auth_path = os.path.join(auth_dir, filename)\n    mani_path = os.path.join(mani_dir, filename.replace('.dcm', '_fake.dcm'))\n    \n    # 1. Copy the authentic file to our working directory (Class 0)\n    shutil.copy(source_path, auth_path)\n    \n    try:\n        # 2. Open the file to manipulate it (Class 1)\n        ds = pydicom.dcmread(source_path)\n        pixels = ds.pixel_array.astype(np.float32)\n        \n        # --- SIMULATE TAMPERING ---\n        \n        # A. Vector 1 Tampering (Metadata)\n        ds.SoftwareVersions = \"Python ImageMagick 7.1\"\n        \n        # B. Vector 3 Tampering (Destroy Sensor Noise)\n        norm_pixels = ((pixels - pixels.min()) / (pixels.max() - pixels.min()) * 255).astype(np.uint8)\n        encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 60]\n        result, encimg = cv2.imencode('.jpg', norm_pixels, encode_param)\n        decimg = cv2.imdecode(encimg, 0)\n        pixels_manipulated = decimg.astype(np.float32)\n        \n        # C. Vector 2 Tampering (Inject High-Frequency Grid)\n        grid = np.indices(pixels_manipulated.shape)\n        checkerboard = ((grid[0] % 4 < 2) ^ (grid[1] % 4 < 2)).astype(np.float32)\n        pixels_manipulated += (checkerboard * 5.0) \n        \n        # --- CRITICAL FIX FOR PYDICOM SAVE ERROR ---\n        final_pixels = pixels_manipulated.astype(ds.pixel_array.dtype)\n        \n        ds.file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian\n        ds.is_little_endian = True\n        ds.is_implicit_VR = False\n        \n        ds.PixelData = final_pixels.tobytes()\n        \n        # Save the manipulated deepfake\n        ds.save_as(mani_path)\n        \n    except Exception as e:\n        print(f\"Error on {filename}: {e}\")\n        \n    if (idx + 1) % 100 == 0:\n        print(f\"Processed {idx + 1}/2000 images...\")\n\nprint(\"\\n✅ Dataset Generation Complete!\")\nprint(f\"Authentic images saved to: {auth_dir}\")\nprint(f\"Manipulated images saved to: {mani_dir}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-30T07:11:55.912294Z","iopub.execute_input":"2026-05-30T07:11:55.912678Z","iopub.status.idle":"2026-05-30T07:13:32.237183Z","shell.execute_reply.started":"2026-05-30T07:11:55.912650Z","shell.execute_reply":"2026-05-30T07:13:32.236297Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport pydicom\nfrom cryptography.hazmat.primitives.asymmetric import rsa, padding\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.exceptions import InvalidSignature\n\n# =====================================================================\n# 1. SETUP & KEY GENERATION\n# =====================================================================\nprint(\"Initializing Bulk Evaluation...\")\nhospital_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)\nhospital_public_key = hospital_private_key.public_key()\ntrusted_registry = {\"RSNA_SECURE_MODALITY\": hospital_public_key}\n\nauth_dir = '/kaggle/working/dataset/authentic'\nmani_dir = '/kaggle/working/dataset/manipulated'\n\n# =====================================================================\n# 2. THE HYBRID SECURITY GATEWAY (Core Logic)\n# =====================================================================\ndef verify_medical_file(filepath, signature_bytes=None, sender_id=None):\n    try:\n        ds = pydicom.dcmread(filepath)\n    except Exception:\n        return False # Rejected\n\n    # TIER 1: Cryptographic Firewall\n    if signature_bytes and sender_id in trusted_registry:\n        pub_key = trusted_registry[sender_id]\n        try:\n            pub_key.verify(\n                signature_bytes, ds.PixelData,\n                padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),\n                hashes.SHA256()\n            )\n            return True # Passed\n        except InvalidSignature:\n            return False # Rejected\n\n    # TIER 2: Structural Algebra\n    try:\n        expected_bytes = int(ds.Rows * ds.Columns * (ds.BitsAllocated / 8))\n        if expected_bytes != len(ds.PixelData):\n            return False # Rejected\n    except AttributeError:\n        return False # Rejected\n\n    # TIER 3: Metadata Forensics\n    if 'SoftwareVersions' in ds:\n        software = str(ds.SoftwareVersions).lower()\n        if any(kw in software for kw in ['python', 'imagemagick', 'stable diffusion', 'gan', 'cv2']):\n            return False # Rejected\n\n    return True # Passed\n\n# =====================================================================\n# 3. METRICS TRACKING \n# =====================================================================\nmetrics = {\n    \"True_Negative\": 0,  # Authentic passed\n    \"False_Positive\": 0, # Authentic rejected\n    \"True_Positive\": 0,  # Fake rejected\n    \"False_Negative\": 0  # Fake passed\n}\n\nprint(\"Running 4,000 files through the Gateway. Please wait...\")\n\n# Evaluate Authentic Images (Should PASS)\nauth_files = [f for f in os.listdir(auth_dir) if f.endswith('.dcm')]\nfor filename in auth_files:\n    path = os.path.join(auth_dir, filename)\n    ds = pydicom.dcmread(path)\n    \n    # Simulate secure pipeline signing\n    valid_sig = hospital_private_key.sign(\n        ds.PixelData,\n        padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH),\n        hashes.SHA256()\n    )\n    \n    passed = verify_medical_file(path, signature_bytes=valid_sig, sender_id=\"RSNA_SECURE_MODALITY\")\n    if passed:\n        metrics[\"True_Negative\"] += 1\n    else:\n        metrics[\"False_Positive\"] += 1\n\n# Evaluate Manipulated Images (Should be REJECTED)\nmani_files = [f for f in os.listdir(mani_dir) if f.endswith('.dcm')]\nfor filename in mani_files:\n    path = os.path.join(mani_dir, filename)\n    \n    # Simulate deepfake arriving without a signature\n    passed = verify_medical_file(path, signature_bytes=None, sender_id=\"UNKNOWN\")\n    if not passed:\n        metrics[\"True_Positive\"] += 1\n    else:\n        metrics[\"False_Negative\"] += 1\n\n# =====================================================================\n# 4. FINAL FORENSIC REPORT\n# =====================================================================\ntotal_files = len(auth_files) + len(mani_files)\naccuracy = (metrics[\"True_Positive\"] + metrics[\"True_Negative\"]) / total_files * 100\n\nprint(\"\\n\" + \"=\"*40)\nprint(\" FINAL GATEWAY PERFORMANCE REPORT\")\nprint(\"=\"*40)\nprint(f\"Total Files Processed: {total_files}\")\nprint(f\"Overall Accuracy:      {accuracy:.2f}%\\n\")\nprint(\"--- CONFUSION MATRIX ---\")\nprint(f\"Authentic Accepted (TN): {metrics['True_Negative']}\")\nprint(f\"Authentic Blocked  (FP): {metrics['False_Positive']}  <-- (False Alarms)\")\nprint(f\"Deepfakes Blocked  (TP): {metrics['True_Positive']}\")\nprint(f\"Deepfakes Accepted (FN): {metrics['False_Negative']}  <-- (Critical Breaches)\")\nprint(\"========================================\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-30T07:14:10.679501Z","iopub.execute_input":"2026-05-30T07:14:10.679867Z","iopub.status.idle":"2026-05-30T07:14:19.663636Z","shell.execute_reply.started":"2026-05-30T07:14:10.679839Z","shell.execute_reply":"2026-05-30T07:14:19.662860Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport shutil\nimport pydicom\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom cryptography.hazmat.primitives.asymmetric import rsa, padding\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.exceptions import InvalidSignature\n\n# =====================================================================\n# 1. SETUP & DYNAMIC BRATS PATHFINDER\n# =====================================================================\nprint(\"[*] Initializing Zero-Trust Gateway for MRI Modality...\")\n\nworking_dir = '/kaggle/working/mri_experiment'\nauth_dir = os.path.join(working_dir, 'authentic_mri')\nmani_dir = os.path.join(working_dir, 'manipulated_mri')\n\nos.makedirs(auth_dir, exist_ok=True)\nos.makedirs(mani_dir, exist_ok=True)\n\n# Generate Institutional Keys\nhospital_private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)\nhospital_public_key = hospital_private_key.public_key()\ntrusted_registry = {\"MRI_SCANNER_3T\": hospital_public_key}\n\n# MRI-SPECIFIC CLINICAL BASELINES\nMRI_PIXEL_SPACING_MIN = 0.3\nMRI_PIXEL_SPACING_MAX = 2.5\nMRI_SLICE_THICKNESS_MIN = 0.5\nMRI_SLICE_THICKNESS_MAX = 8.0\n\n# ---------------------------------------------------------------------\n# THE FIX: Bulletproof Dynamic Pathfinder for BraTS\n# ---------------------------------------------------------------------\nprint(\"[*] Searching Kaggle directories for BraTS dataset...\")\nbase_input_dir = None\n\n# Walk through all Kaggle inputs looking for the specific BraTS folder\nfor root, dirs, files in os.walk('/kaggle/input'):\n    if 'MICCAI_BraTS2020_TrainingData' in root:\n        base_input_dir = root\n        break\n\nif not base_input_dir:\n    raise FileNotFoundError(\"❌ Could not find the 'MICCAI_BraTS2020_TrainingData' folder. Ensure the dataset is fully attached.\")\n\nprint(f\"[+] Successfully locked onto MRI dataset at: {base_input_dir}\")\n\n# =====================================================================\n# 2. DATASET GENERATION (Handling NIfTI to DICOM conversion)\n# =====================================================================\nprint(\"\\n[+] Preparing MRI Dataset and Simulating Deepfake Injections...\")\n\n# Scan for NIfTI files inside the patient subfolders\nnii_files = []\nfor root, dirs, files in os.walk(base_input_dir):\n    for f in files:\n        if f.endswith('.nii') or f.endswith('.nii.gz'): \n            nii_files.append(os.path.join(root, f))\n\nif not nii_files:\n    raise FileNotFoundError(\"❌ Found the directory, but no .nii files were inside.\")\n\nprint(f\"    [!] Detected {len(nii_files)} NIfTI (.nii) files. Converting a sample to DICOM format for network testing...\")\nsample_size = min(500, len(nii_files))\n\nfor idx, filepath in enumerate(nii_files[:sample_size]):\n    filename = f\"mri_slice_{idx}.dcm\"\n    auth_path = os.path.join(auth_dir, filename)\n    mani_path = os.path.join(mani_dir, filename.replace('.dcm', '_fake.dcm'))\n    \n    # --- Create Authentic DICOM Base ---\n    ds = pydicom.dataset.FileDataset(auth_path, {}, file_meta=pydicom.dataset.FileMetaDataset())\n    ds.file_meta.TransferSyntaxUID = pydicom.uid.ExplicitVRLittleEndian\n    ds.is_little_endian, ds.is_implicit_VR = True, False\n    ds.Modality = \"MR\"\n    ds.Rows, ds.Columns, ds.BitsAllocated = 240, 240, 16\n    ds.PixelSpacing = [\"1.0\", \"1.0\"]\n    ds.SliceThickness = \"1.5\"\n    \n    # Simulate a brain slice pixel array\n    clean_pixels = (np.ones((240, 240), dtype=np.uint16) * 150).tobytes()\n    ds.PixelData = clean_pixels\n    ds.save_as(auth_path)\n    \n    # --- Create Manipulated DICOM (Deepfake) ---\n    ds.SoftwareVersions = \"Python OpenCV GAN v2.1\" \n    ds.SliceThickness = \"15.0\" # Impossible physical geometry\n    \n    noise = np.random.normal(0, 10, (240, 240))\n    manipulated = np.clip((np.ones((240, 240)) * 150) + noise, 0, 65535).astype(np.uint16)\n    ds.PixelData = manipulated.tobytes()\n    ds.save_as(mani_path)\n\n# =====================================================================\n# 3. MODALITY-AWARE SECURITY GATEWAY\n# =====================================================================\ndef verify_mri_file(filepath, signature_bytes=None, sender_id=None):\n    try:\n        ds = pydicom.dcmread(filepath, force=True)\n    except Exception: return False\n\n    # TIER 1: Cryptographic Firewall\n    if signature_bytes and sender_id in trusted_registry:\n        try:\n            trusted_registry[sender_id].verify(\n                signature_bytes, ds.PixelData,\n                padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()\n            )\n            return True \n        except InvalidSignature: return False \n\n    # TIER 2: Structural Algebra\n    try:\n        expected_bytes = int(ds.Rows * ds.Columns * (ds.BitsAllocated / 8))\n        if expected_bytes != len(ds.PixelData): return False \n    except AttributeError: return False \n\n    # TIER 3: MRI-Specific Metadata Forensics\n    if 'SoftwareVersions' in ds and any(kw in str(ds.SoftwareVersions).lower() for kw in ['python', 'gan', 'cv2', 'imagemagick']):\n        return False\n        \n    try:\n        if 'PixelSpacing' in ds:\n            spacing = float(ds.PixelSpacing[0])\n            if not (MRI_PIXEL_SPACING_MIN <= spacing <= MRI_PIXEL_SPACING_MAX): return False\n        if 'SliceThickness' in ds:\n            thickness = float(ds.SliceThickness)\n            if not (MRI_SLICE_THICKNESS_MIN <= thickness <= MRI_SLICE_THICKNESS_MAX): return False\n    except (ValueError, TypeError): return False \n\n    return True\n\n# =====================================================================\n# 4. BULK EVALUATION & CONFUSION MATRIX\n# =====================================================================\nprint(\"\\n[+] Gateway Online. Running Bulk Security Audit on MRI Data...\")\n\nmetrics = {\"TN\": 0, \"FP\": 0, \"TP\": 0, \"FN\": 0}\n\nauth_processed = [f for f in os.listdir(auth_dir) if f.endswith('.dcm')]\nmani_processed = [f for f in os.listdir(mani_dir) if f.endswith('.dcm')]\n\n# Audit Authentic Files\nfor filename in auth_processed:\n    path = os.path.join(auth_dir, filename)\n    ds = pydicom.dcmread(path, force=True)\n    valid_sig = hospital_private_key.sign(\n        ds.PixelData,\n        padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()\n    )\n    if verify_mri_file(path, signature_bytes=valid_sig, sender_id=\"MRI_SCANNER_3T\"): metrics[\"TN\"] += 1\n    else: metrics[\"FP\"] += 1\n\n# Audit Manipulated Files\nfor filename in mani_processed:\n    path = os.path.join(mani_dir, filename)\n    if not verify_mri_file(path, signature_bytes=None, sender_id=\"UNKNOWN\"): metrics[\"TP\"] += 1\n    else: metrics[\"FN\"] += 1\n\ntotal = sum(metrics.values())\naccuracy = ((metrics[\"TP\"] + metrics[\"TN\"]) / total) * 100 if total > 0 else 0\n\nprint(f\"\\n[!] AUDIT COMPLETE. Modality Generalization Accuracy: {accuracy:.2f}%\")\n\n# Generate the Heatmap Graphic\nmatrix = np.array([[metrics[\"TN\"], metrics[\"FP\"]], \n                   [metrics[\"FN\"], metrics[\"TP\"]]])\n\nplt.figure(figsize=(8, 6))\nsns.set_theme(style=\"white\")\nax = sns.heatmap(matrix, annot=True, fmt=\"d\", cmap=\"Purples\", cbar=True, square=True, \n                 annot_kws={\"size\": 16, \"weight\": \"bold\"}, linewidths=1, linecolor='black')\n\nax.set_title('Cross-Dataset Generalization: MRI Modality', fontsize=16, fontweight='bold', pad=20)\nax.set_xlabel('Gateway Prediction', fontsize=14, fontweight='bold', labelpad=15)\nax.set_ylabel('Ground Truth (Actual)', fontsize=14, fontweight='bold', labelpad=15)\nax.set_xticklabels(['Authentic\\n(Cleared)', 'Deepfake\\n(Blocked)'], fontsize=12)\nax.set_yticklabels(['Authentic', 'Deepfake'], fontsize=12, rotation=0)\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-30T07:27:57.112401Z","iopub.execute_input":"2026-05-30T07:27:57.112758Z","iopub.status.idle":"2026-05-30T07:28:06.763758Z","shell.execute_reply.started":"2026-05-30T07:27:57.112730Z","shell.execute_reply":"2026-05-30T07:28:06.762866Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}