File size: 13,733 Bytes
023a05d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import os
# Suppress MediaPipe/Abseil C++ logging noise (Levels: 0 = INFO, 1 = WARNING, 2 = ERROR, 3 = FATAL)
os.environ['GLOG_minloglevel'] = '2'
os.environ['ABSL_MIN_LOG_LEVEL'] = '2'

import cv2
import numpy as np
import pandas as pd
from pathlib import Path
from glob import glob
import scipy.signal
import mediapipe as mp
from concurrent.futures import ThreadPoolExecutor, as_completed

# ==================== DIRECTORY CONFIGURATION ====================
RAW_VIDEO_DIR   = "/home/cristic/data/Bgeorge/mcd_rppg/snapshots/929fb19c5ff2b5c8ed64a7c3a123744346674e88/video/"
PPG_SYNC_DIR    = "/home/cristic/data/Bgeorge/mcd_rppg/snapshots/929fb19c5ff2b5c8ed64a7c3a123744346674e88/ppg_sync/"
CALE_CSV        = "/home/cristic/rppg_project/data/raw/mcd_rppg/db.csv"

# OUTPUT_BASE     = "/home/cristic/rppg_project/data/processed/"
# FACES_DIR       = os.path.join(OUTPUT_BASE, "faces")
# LANDMARKS_DIR   = os.path.join(OUTPUT_BASE, "landmarks")
# ROI_DIR         = os.path.join(OUTPUT_BASE, "roi")
# Output Directories
OUTPUT_BASE     = "/home/cristic/RppG_mediapipe_preprocessed_full_dataset3/"
FACES_DIR       = os.path.join(OUTPUT_BASE, "faces")
LANDMARKS_DIR   = os.path.join(OUTPUT_BASE, "landmarks")
ROI_DIR         = os.path.join(OUTPUT_BASE, "roi")

WINDOW_FRAMES   = 450
VIDEO_FS        = 29.9  # Set to match your video stream profile
NUM_WORKERS     = 40  

# ==================== ORIGINAL REPO UTILITIES ====================
def filter_signal(signal_arr, rate, freq, mode='high', order=4):
    hb_n_freq = freq / (rate / 2)
    b, a = scipy.signal.butter(order, hb_n_freq, mode)
    filtered = scipy.signal.filtfilt(b, a, signal_arr)
    return filtered.astype(signal_arr.dtype)

def bandpass_filter(signal_arr, rate, low_freq=0.5, high_freq=3.5, order=4):
    signal_arr = filter_signal(signal_arr, rate, high_freq, mode='low',  order=order)
    signal_arr = filter_signal(signal_arr, rate, low_freq,  mode='high', order=order)
    return signal_arr

def _next_power_of_2(x):
    return 1 if x == 0 else 2 ** (x - 1).bit_length()

def calculate_fft_hr(ppg_signal, fs=29.9, low_pass=0.5, high_pass=3.5):
    ppg_signal = np.expand_dims(ppg_signal, 0)
    N = _next_power_of_2(ppg_signal.shape[1])
    f_ppg, pxx_ppg = scipy.signal.periodogram(ppg_signal, fs=fs, nfft=N, detrend=False)
    fmask_ppg = np.argwhere((f_ppg >= low_pass) & (f_ppg <= high_pass))
    mask_ppg = np.take(f_ppg, fmask_ppg)
    mask_pxx = np.take(pxx_ppg, fmask_ppg)
    fft_hr = np.take(mask_ppg, np.argmax(mask_pxx, 0))[0] * 60
    return fft_hr

# def get_roi_regions(frame, landmarks, h, w):
#     return np.zeros((8, 32, 32, 3), dtype=np.uint8)
def get_roi_regions(frame, landmarks, h, w):
    """
    Extracts 8 distinct facial tissue patches using specific MediaPipe landmark indices.
    Crops them from the frame, resizes each to 32x32 pixels, and stacks them.
    """
    roi_patches = np.zeros((8, 32, 32, 3), dtype=np.uint8)
    
    # 8 Key groups of landmark IDs corresponding to strong vascular regions
    # (Cheeks, forehead segments, nose bridge, chin)
    roi_landmark_groups = [
        [70, 71, 139, 156],   # 0: Left Forehead
        [300, 301, 368, 383], # 1: Right Forehead
        [117, 118, 101, 50],   # 2: Left Upper Cheek
        [346, 347, 330, 280], # 3: Right Upper Cheek
        [205, 206, 207, 187], # 4: Left Lower Cheek / Jaw area
        [425, 426, 427, 411], # 5: Right Lower Cheek / Jaw area
        [6, 197, 195, 5],     # 6: Nose Bridge
        [199, 200, 18, 42]     # 7: Chin / Lower Lip area
    ]
    
    for idx, group in enumerate(roi_landmark_groups):
        try:
            # 1. Gather all pixel coordinates for the current landmark group
            pts = []
            for lm_idx in group:
                lm = landmarks[lm_idx]
                pt_x = int(lm.x * w)
                pt_y = int(lm.y * h)
                pts.append([pt_x, pt_y])
            
            pts = np.array(pts)
            
            # 2. Compute a tight bounding box around those landmarks
            xmin, ymin = np.min(pts, axis=0)
            xmax, ymax = np.max(pts, axis=0)
            
            # 3. Add dynamic safety margins to make the crop useful
            box_w = xmax - xmin
            box_h = ymax - ymin
            margin_x = int(box_w * 0.1)
            margin_y = int(box_h * 0.1)
            
            xmin = max(0, xmin - margin_x)
            ymin = max(0, ymin - margin_y)
            xmax = min(w, xmax + margin_x)
            ymax = min(h, ymax + margin_y)
            
            # 4. Extract and resize slice if it forms a valid spatial patch
            if (xmax - xmin) > 4 and (ymax - ymin) > 4:
                crop = frame[ymin:ymax, xmin:xmax]
                roi_patches[idx] = cv2.resize(crop, (32, 32))
            else:
                # Fallback to zero placeholder if crop fails bounds
                pass
                
        except Exception:
            # Catch exceptions for edge-of-frame tracking failures gracefully
            pass
            
    return roi_patches
# ==================== CORE PROCESSING WORKER ====================
def process_single_video(task_args):
    video_path, ppg_path, meta_dict, base_name = task_args
    
    BaseOptions = mp.tasks.BaseOptions
    FaceLandmarker = mp.tasks.vision.FaceLandmarker
    FaceLandmarkerOptions = mp.tasks.vision.FaceLandmarkerOptions
    VisionRunningMode = mp.tasks.vision.RunningMode
    
    model_path = "/home/cristic/face_landmarker.task"
    if not os.path.exists(model_path):
        return False, f"[{base_name}] Model missing at: {model_path}"

    options = FaceLandmarkerOptions(
        base_options=BaseOptions(model_asset_path=model_path),
        running_mode=VisionRunningMode.IMAGE,
        num_faces=1
    )
    
    try:
        with FaceLandmarker.create_from_options(options) as landmarker:
            # 1. Parse frame bounds
            cap = cv2.VideoCapture(video_path)
            if not cap.isOpened():
                return False, f"[{base_name}] Failed to open stream."
            
            w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            
            total_frames = 0
            while cap.grab():
                total_frames += 1
            cap.release()
            
            if total_frames < WINDOW_FRAMES:
                return False, f"[{base_name}] Skipped: Frame count ({total_frames}) under window."

            # 2. Extract and match original repository 1D PPG wave rules
            try:
                raw_matrix = np.loadtxt(ppg_path, dtype=np.float32)
                
                # Enforce strict 1D selection of Column 1 (the physiological wave channel)
                if raw_matrix.ndim > 1:
                    raw_ppg_wave = raw_matrix[:, 1].copy()
                else:
                    raw_ppg_wave = raw_matrix.copy()
                    
                # Fix the artifact spike at Index-0 to prevent filter distortion
                if len(raw_ppg_wave) > 1:
                    raw_ppg_wave[0] = raw_ppg_wave[1]
                    
            except Exception as e:
                return False, f"[{base_name}] Matrix parse fail: {e}"

            # 3. Chunk Processing
            cap = cv2.VideoCapture(video_path)
            num_chunks = total_frames // WINDOW_FRAMES
            
            for chunk_idx in range(num_chunks):
                faces_buf = []
                landmarks_buf = []
                roi_slices_buf = []
                
                start_f = chunk_idx * WINDOW_FRAMES
                end_f = start_f + WINDOW_FRAMES
                
                # Slice target wave segment
                ppg_chunk = raw_ppg_wave[start_f:min(end_f, len(raw_ppg_wave))].copy()
                if len(ppg_chunk) < WINDOW_FRAMES:
                    ppg_chunk = np.pad(ppg_chunk, (0, WINDOW_FRAMES - len(ppg_chunk)), mode='edge')
                
                # Apply Repository filtering and standardization sequence
                ppg_chunk = bandpass_filter(ppg_chunk, rate=VIDEO_FS, low_freq=0.5, high_freq=3.5, order=4)
                ppg_chunk -= ppg_chunk.mean()
                ppg_chunk /= (ppg_chunk.std() + 1e-9)
                
                # Compute HR via padded original repo FFT logic
                calculated_hr = int(np.round(calculate_fft_hr(ppg_chunk, fs=VIDEO_FS)))
                
                for _ in range(WINDOW_FRAMES):
                    ret, frame = cap.read()
                    if not ret:
                        break
                        
                    rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                    mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb_frame)
                    detection_result = landmarker.detect(mp_image)
                    
                    if detection_result.face_landmarks:
                        landmarks = detection_result.face_landmarks[0]
                        coords = np.array([[lm.x * w, lm.y * h] for lm in landmarks], dtype=np.float32)
                        all_pts = np.array([[int(lm.x * w), int(lm.y * h)] for lm in landmarks])
                        xmin, ymin = np.clip(np.min(all_pts, axis=0), 0, [w, h])
                        xmax, ymax = np.clip(np.max(all_pts, axis=0), 0, [w, h])
                        
                        if (xmax - xmin) > 0 and (ymax - ymin) > 0:
                            face_crop = cv2.resize(frame[ymin:ymax, xmin:xmax], (128, 128))
                        else:
                            face_crop = np.zeros((128, 128, 3), dtype=np.uint8)
                        roi_regions = get_roi_regions(frame, landmarks, h, w)
                    else:
                        coords = landmarks_buf[-1] if landmarks_buf else np.zeros((478, 2), dtype=np.float32)
                        face_crop = faces_buf[-1] if faces_buf else np.zeros((128, 128, 3), dtype=np.uint8)
                        roi_regions = roi_slices_buf[-1] if roi_slices_buf else np.zeros((8, 32, 32, 3), dtype=np.uint8)
                        
                    faces_buf.append(face_crop)
                    landmarks_buf.append(coords)
                    roi_slices_buf.append(roi_regions)
                
                if len(faces_buf) < WINDOW_FRAMES:
                    break 
                    
                chunk_name = f"{base_name}_chunk{chunk_idx}"
                
                np.save(os.path.join(FACES_DIR, f"{chunk_name}_faces.npy"), np.array(faces_buf))
                np.save(os.path.join(LANDMARKS_DIR, f"{chunk_name}_landmarks.npy"), np.array(landmarks_buf))
                
                np.savez_compressed(
                    os.path.join(ROI_DIR, f"{chunk_name}.npz"),
                    roi=np.array(roi_slices_buf),
                    ppg=ppg_chunk.astype('float32'),  # Normalized continuous waveform array matching repo layout
                    hr=calculated_hr,                 # The strict integer FFT tracking parameter
                    subject_id=str(meta_dict.get('patient_id', meta_dict.get('id', ''))),
                    age=float(meta_dict.get('age', 0)),
                    sex=str(meta_dict.get('sex', '')),
                    bmi=float(meta_dict.get('bmi', 0)),
                    systolic=float(meta_dict.get('upper_ap', 0)),
                    diastolic=float(meta_dict.get('lower_ap', 0)),
                    spo2=float(meta_dict.get('saturation', 0)),
                    temperature=float(meta_dict.get('temperature', 0))
                )
                
            cap.release()
            return True, f"[{base_name}] Completed into {num_chunks} chunks."
            
    except Exception as e:
        return False, f"[{base_name}] Process Exception: {str(e)}"

def main():
    os.makedirs(FACES_DIR, exist_ok=True)
    os.makedirs(LANDMARKS_DIR, exist_ok=True)
    os.makedirs(ROI_DIR, exist_ok=True)
    
    print("[*] Indexing raw data assets...")
    video_files = sorted(glob(os.path.join(RAW_VIDEO_DIR, "*.avi")) + glob(os.path.join(RAW_VIDEO_DIR, "*.mp4")))
    
    if not os.path.exists(CALE_CSV):
        print(f"[!] Metadata index CSV missing at: {CALE_CSV}")
        return
        
    df_meta = pd.read_csv(CALE_CSV)
    task_queue = []
    
    for v_path in video_files:
        b_name = Path(v_path).stem
        p_path = os.path.join(PPG_SYNC_DIR, f"{b_name}.txt")
        if not os.path.exists(p_path):
            continue
            
        matching_rows = df_meta[df_meta['video'].str.contains(b_name, na=False)]
        meta_dict = matching_rows.iloc[0].to_dict() if not matching_rows.empty else {}
        task_queue.append((v_path, p_path, meta_dict, b_name))
        
    print(f"[+] Total verified matches ready to execute: {len(task_queue)}")
    print(f"[*] Instantiating ThreadPoolExecutor pipeline using {NUM_WORKERS} concurrent execution instances...")
    
    success_count = 0
    with ThreadPoolExecutor(max_workers=NUM_WORKERS) as executor:
        futures = {executor.submit(process_single_video, task): task for task in task_queue}
        
        for idx, future in enumerate(as_completed(futures)):
            success, message = future.result()
            if success:
                success_count += 1
            else:
                print(f"[!] Alert: {message}")
                
            if idx % 50 == 0:
                print(f"Progress checkpoint: {idx}/{len(task_queue)} tracks processed...")
                
    print("\n" + "="*50)
    print(f" PREPROCESSING ARCHITECTURE INGESTION DONE!")
    print(f" Successfully complete targets: {success_count} / {len(task_queue)}")
    print("="*50)

if __name__ == "__main__":
    main()