File size: 12,570 Bytes
9deebf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
"""
RV (Full Remote Viewing) dataset processor.

Processes remote viewing test data with dimensional attribute scoring.
Format: 24-29 columns with user, timestamps, image info, 16 attribute scores,
accuracy/relevance/form metrics, total score, keywords, and trial info.

More complex than RVQ - uses continuous scoring (0-100) instead of binary hit/miss.
"""

from pathlib import Path
from typing import List, Dict, Any, Optional
from datetime import datetime
import pandas as pd
import re

from ..core.base_classes import BaseProcessor
from ..core.config import Config
from ..core.exceptions import ProcessorError
from ..cleaners.encoding_cleaner import EncodingCleaner
from ..cleaners.delimiter_cleaner import DelimiterCleaner
from ..cleaners.temporal_parser import TemporalParser


class RVProcessor(BaseProcessor):
    """
    Processes RV (Full Remote Viewing) data.

    Format: 24-29 columns
    - user_id, start_time, end_time, image_filename, image_number,
    - 16 attribute scores (sr[0] through sr[15]),
    - accuracy, relevance, form, total_score,
    - keywords, trial_number, method, num_keyword_matches

    Users view a target image and describe it using dimensional attributes
    (rounded/angular, linear, etc.). Scores based on how well description
    matches the actual image attributes.
    """

    # File discovery patterns
    FILE_PATTERNS = ['rv[0-9]*.dat']

    # Attribute score column names (16 attributes)
    ATTRIBUTE_COLUMNS = [f'attr_{i:02d}' for i in range(16)]

    # Column definitions
    COLUMNS_BASE = [
        'user_id', 'start_time', 'end_time', 'image_filename', 'image_number'
    ] + ATTRIBUTE_COLUMNS + [
        'accuracy', 'relevance', 'form', 'total_score',
        'keywords', 'trial_number', 'method', 'num_keyword_matches'
    ]

    COLUMNS_UNIFIED = [
        'user_id', 'start_time', 'end_time',
        'image_filename', 'image_number'
    ] + ATTRIBUTE_COLUMNS + [
        'accuracy', 'relevance', 'form', 'total_score',
        'keywords', 'trial_number', 'method', 'num_keyword_matches',
        'file_date', 'source_file', 'source_row_number'
    ]

    def __init__(self, config: Config):
        """
        Initialize RV processor.

        Args:
            config: Configuration object
        """
        super().__init__(config, 'rv')

        # Initialize cleaners
        self.encoding_cleaner = EncodingCleaner(config, self.errata_logger)
        self.delimiter_cleaner = DelimiterCleaner(config, self.errata_logger)
        self.temporal_parser = TemporalParser(config, self.errata_logger)

        # Statistics
        self.stats = {
            'files_processed': 0,
            'files_failed': 0,
            'rows_total': 0,
            'rows_valid': 0,
            'rows_invalid': 0,
            'method_original': 0,
            'method_match_judges': 0,
            'method_keywords': 0
        }

    def extract_file_date(self, file_path: Path) -> Optional[datetime]:
        """
        Extract date from filename (rvYYMMDD.dat).

        Args:
            file_path: Path to file

        Returns:
            datetime object or None
        """
        match = re.search(r'rv(\d{6})\.dat', file_path.name)
        if not match:
            return None

        date_str = match.group(1)
        return self.temporal_parser.extract_date_from_filename(file_path.name)

    def process_file(self, file_path: Path, pre_cleaned_text: Optional[str] = None) -> Optional[pd.DataFrame]:
        """
        Process a single RV file.

        Args:
            file_path: Path to file
            pre_cleaned_text: Pre-cleaned text from parallel batch cleaning.
                If None, cleans the file inline (backward compat).

        Returns:
            DataFrame or None if processing fails
        """
        try:
            # Use pre-cleaned text if available, otherwise clean inline
            if pre_cleaned_text is not None:
                text = pre_cleaned_text
            else:
                text = self.encoding_cleaner.clean(file_path)
                text = self.delimiter_cleaner.clean(text, file_path=str(file_path))

            # Parse as CSV using Python's csv module to handle variable columns
            from io import StringIO
            import csv

            reader = csv.reader(StringIO(text), skipinitialspace=True)
            rows = list(reader)

            if not rows:
                self.errata_logger.log_error(
                    'empty_file',
                    'File is empty after CSV parsing - entire file omitted',
                    file_path=str(file_path),
                    scope='file'
                )
                return None

            # Convert to DataFrame
            df = pd.DataFrame(rows)

            if df.empty:
                self.errata_logger.log_error(
                    'empty_file',
                    'File is empty or has no valid rows - entire file omitted',
                    file_path=str(file_path),
                    scope='file'
                )
                return None

            # Check minimum column count (24)
            column_counts = df.notna().sum(axis=1)
            insufficient_cols = column_counts < 24

            if insufficient_cols.all():
                self.errata_logger.log_error(
                    'insufficient_columns',
                    'All rows have < 24 columns - entire file omitted',
                    file_path=str(file_path),
                    scope='file'
                )
                return None

            # Filter rows with insufficient columns
            if insufficient_cols.any():
                self.errata_logger.log_error(
                    'insufficient_columns',
                    f'{insufficient_cols.sum()} rows with < 24 columns',
                    file_path=str(file_path),
                    scope='row'
                )
                df = df[~insufficient_cols]

            # Assign column names based on actual column count
            max_cols = len(df.columns)
            if max_cols >= 29:
                # Drop extra columns if more than 29 (early files have extra columns)
                if max_cols > 29:
                    # Log that we're dropping extra columns from early files
                    self.errata_logger.log_error(
                        'extra_columns_dropped',
                        f'File has {max_cols} columns, dropping {max_cols - 29} extra columns from early schema',
                        file_path=str(file_path),
                        scope='row'
                    )
                    df = df.iloc[:, :29]
                df.columns = self.COLUMNS_BASE[:29]
            elif max_cols >= 24:
                df.columns = self.COLUMNS_BASE[:max_cols]
            else:
                self.errata_logger.log_error(
                    'insufficient_columns',
                    f'Max columns {max_cols} < 24 - entire file omitted',
                    file_path=str(file_path),
                    scope='file'
                )
                return None

            # Add metadata
            file_date = self.extract_file_date(file_path)
            df['file_date'] = file_date

            # Add audit columns (source file and row numbers)
            df['source_file'] = file_path.name
            df['source_row_number'] = range(1, len(df) + 1)

            # Filter test users
            test_user_mask = df['user_id'].astype(str).str.contains('_test9', na=False)
            if test_user_mask.any():
                df = df[~test_user_mask]

            # Validate and clean
            df = self.validate_dataframe(df, file_path)

            if df.empty:
                return None

            # Ensure all unified columns exist AFTER validation
            for col in self.COLUMNS_UNIFIED:
                if col not in df.columns:
                    df[col] = None

            # Reorder to unified schema
            df = df[self.COLUMNS_UNIFIED]

            # Update stats
            self.stats['files_processed'] += 1
            self.stats['rows_valid'] += len(df)

            # Track method counts
            if 'method' in df.columns:
                method_counts = df['method'].value_counts()
                for method_val, count in method_counts.items():
                    if pd.notna(method_val):
                        method_val = int(method_val)
                        if method_val % 10 == 0:  # 0 or 10
                            self.stats['method_original'] += count
                        elif method_val % 10 == 3:  # 3 or 13
                            self.stats['method_match_judges'] += count
                        elif method_val == 9:
                            self.stats['method_keywords'] += count

            return df

        except Exception as e:
            import traceback
            self.errata_logger.log_error(
                'file_processing_failed',
                f'{type(e).__name__}: {e} - entire file omitted',
                file_path=str(file_path),
                scope='file',
                context={'traceback': traceback.format_exc()},
            )
            self.stats['files_failed'] += 1
            return None

    def validate_dataframe(self, df: pd.DataFrame, file_path: Path) -> pd.DataFrame:
        """
        Validate and clean DataFrame.

        Args:
            df: Input DataFrame
            file_path: Source file path

        Returns:
            Cleaned DataFrame
        """
        initial_count = len(df)
        valid_mask = pd.Series([True] * len(df), index=df.index)


        # Validate user_id length
        if 'user_id' in df.columns:
            long_users = df['user_id'].str.len() > 64
            if long_users.any():
                valid_mask &= ~long_users
                self.errata_logger.log_error(
                    'user_id_too_long',
                    f'{long_users.sum()} rows with user_id > 64 chars',
                    file_path=str(file_path),
                    scope='row'
                )

        # Validate and clamp total_score (0-100)
        if 'total_score' in df.columns:
            df['total_score'] = self.to_numeric_logged(df['total_score'], 'total_score', str(file_path))
            # Clamp scores to 0-100 as per Perl code
            df.loc[df['total_score'] < 0, 'total_score'] = 0
            df.loc[df['total_score'] > 100, 'total_score'] = 100

        # Validate num_keyword_matches (0-5)
        if 'num_keyword_matches' in df.columns:
            df['num_keyword_matches'] = self.to_numeric_logged(df['num_keyword_matches'], 'num_keyword_matches', str(file_path))
            invalid_nwm = (df['num_keyword_matches'] < 0) | (df['num_keyword_matches'] > 5)
            if invalid_nwm.any():
                # Log but don't filter - just clamp
                self.errata_logger.log_error(
                    'num_keyword_matches_out_of_range',
                    f'{invalid_nwm.sum()} rows with num_keyword_matches not in 0-5',
                    file_path=str(file_path),
                    scope='row'
                )
                df.loc[df['num_keyword_matches'] < 0, 'num_keyword_matches'] = 0
                df.loc[df['num_keyword_matches'] > 5, 'num_keyword_matches'] = 5

        # Parse timestamps
        if 'start_time' in df.columns:
            df['start_time'] = self.temporal_parser.parse_dates_vectorized(
                df['start_time'], file_path=str(file_path)
            )

        if 'end_time' in df.columns:
            df['end_time'] = self.temporal_parser.parse_dates_vectorized(
                df['end_time'], file_path=str(file_path)
            )

        # Convert numeric columns
        numeric_cols = [
            'image_number', 'accuracy', 'relevance', 'form', 'total_score',
            'trial_number', 'method', 'num_keyword_matches'
        ] + self.ATTRIBUTE_COLUMNS

        for col in numeric_cols:
            if col in df.columns:
                df[col] = self.to_numeric_logged(df[col], col, str(file_path))

        # Filter to valid rows
        df_valid = df[valid_mask].copy()

        invalid_count = initial_count - len(df_valid)
        if invalid_count > 0:
            self.errata_logger.log_file_summary(
                str(file_path),
                'partial',
                initial_count,
                len(df_valid),
                invalid_count
            )

        return df_valid

    def get_stats(self) -> Dict[str, Any]:
        """Get processing statistics."""
        return self.stats.copy()