Skip to content

Real Upload Callbacks

real_upload_callbacks

Real Upload Callbacks - BioRemPP v1.0

Callbacks for handling file uploads and validation.

Classes

Functions

register_real_upload_callbacks

register_real_upload_callbacks(app)

Register real upload callbacks.

Parameters:

Name Type Description Default
app Dash

Dash application instance

required
Source code in src/presentation/callbacks/real_upload_callbacks.py
 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
def register_real_upload_callbacks(app):
    """
    Register real upload callbacks.

    Parameters
    ----------
    app : Dash
        Dash application instance
    """
    logger.info("=" * 60)
    logger.info("Registering REAL UPLOAD callbacks...")
    logger.info("=" * 60)

    @callback(
        [
            Output("upload-status", "children"),
            Output("upload-data-store", "data"),
            Output("file-info-display", "children"),
        ],
        Input("upload-component", "contents"),
        State("upload-component", "filename"),
        prevent_initial_call=True,
    )
    @instrument_callback("upload.handle_upload")
    def handle_upload(contents, filename):
        """
        Handle file upload with comprehensive validation.

        Performs server-side validation including:
        - File size limits
        - Encoding validation (UTF-8/latin-1)
        - Filename sanitization
        - Content format validation
        - Sample and KO count limits
        - Sample name sanitization

        Parameters
        ----------
        contents : str
            Base64 encoded file contents
        filename : str
            Original filename

        Returns
        -------
        tuple
            (status_alert, file_data, file_info_card)
        """
        if contents is None:
            raise PreventUpdate

        try:
            # ============================================================
            # STEP 1: Decode Base64
            # ============================================================
            try:
                _, content_string = contents.split(",")
                decoded = base64.b64decode(content_string)
            except (ValueError, Exception) as e:
                logger.error(f"Base64 decode failed: {e}")
                _record_upload_metrics("upload", "decode_failed")
                return (
                    create_error_alert(
                        "Invalid File Format",
                        "Unable to read file. Please upload a valid text file.",
                        suggestions=[
                            "Ensure file is in text format (.txt)",
                            "Check file is not corrupted",
                        ],
                    ),
                    no_update,
                    None,  # Clear file info display on error
                )

            # ============================================================
            # STEP 2: Validate File Size (SERVER-SIDE)
            # ============================================================
            is_valid, error_msg = ValidationService.validate_file_size(
                size_bytes=len(decoded), max_bytes=settings.UPLOAD_MAX_SIZE_BYTES
            )

            if not is_valid:
                logger.warning(f"File size validation failed: {error_msg}")
                _record_upload_metrics(
                    "upload",
                    "file_size_exceeded",
                    size_bytes=len(decoded),
                )
                return (
                    create_error_alert(
                        "File Size Exceeded",
                        error_msg,
                        suggestions=[
                            f"Reduce file size to under {settings.UPLOAD_MAX_SIZE_MB} MB",
                            "Remove unnecessary samples or KO entries",
                            "Split into multiple smaller files",
                        ],
                    ),
                    no_update,
                    None,  # Clear file info display on error
                )

            # ============================================================
            # STEP 3: Validate and Decode Encoding
            # ============================================================
            is_valid, file_content, error_msg = ValidationService.validate_encoding(
                decoded
            )

            if not is_valid:
                logger.error(f"Encoding validation failed: {error_msg}")
                _record_upload_metrics(
                    "upload",
                    "encoding_failed",
                    size_bytes=len(decoded),
                )
                return (
                    create_error_alert(
                        "Encoding Error",
                        error_msg,
                        suggestions=[
                            "Save file with UTF-8 encoding",
                            "Use a text editor that supports UTF-8",
                            "Check for special characters",
                        ],
                    ),
                    no_update,
                    None,  # Clear file info display on error
                )

            # ============================================================
            # STEP 4: Sanitize Filename
            # ============================================================
            safe_filename = SanitizationService.sanitize_filename(filename)

            # ============================================================
            # STEP 5: Comprehensive Content Validation
            # ============================================================
            is_valid, error_msg = ValidationService.validate_raw_input(file_content)

            if not is_valid:
                logger.warning(f"Content validation failed: {error_msg}")
                _record_upload_metrics(
                    "upload",
                    "content_invalid",
                    size_bytes=len(decoded),
                )
                return (
                    create_error_alert(
                        "Invalid File Format",
                        error_msg,
                        suggestions=[
                            "Check file format: lines starting with '>' for samples",
                            "Ensure KO IDs follow format: K + 5 digits (e.g., K00001)",
                            "See example file for reference",
                        ],
                    ),
                    no_update,
                    None,  # Clear file info display on error
                )

            # ============================================================
            # STEP 6: Count Samples and KOs for Limit Validation
            # ============================================================
            lines = file_content.strip().split("\n")
            sample_count = sum(1 for line in lines if line.startswith(">"))
            ko_count = sum(1 for line in lines if line.strip().startswith("K"))

            # ============================================================
            # STEP 7: Validate Sample Count Limit
            # ============================================================
            is_valid, error_msg = ValidationService.validate_sample_count(
                sample_count=sample_count, max_samples=settings.UPLOAD_SAMPLE_LIMIT
            )

            if not is_valid:
                logger.warning(f"Sample count limit exceeded: {error_msg}")
                _record_upload_metrics(
                    "upload",
                    "sample_limit_exceeded",
                    size_bytes=len(decoded),
                )
                return (
                    create_error_alert(
                        "Sample Limit Exceeded",
                        error_msg,
                        suggestions=[
                            f"Reduce to {settings.UPLOAD_SAMPLE_LIMIT} samples or fewer",
                            "Split dataset into multiple files",
                            "Remove duplicate or unnecessary samples",
                        ],
                    ),
                    no_update,
                    None,  # Clear file info display on error
                )

            # ============================================================
            # STEP 8: Validate KO Count Limit
            # ============================================================
            is_valid, error_msg = ValidationService.validate_ko_count(
                ko_count=ko_count, max_kos=settings.UPLOAD_KO_LIMIT
            )

            if not is_valid:
                logger.warning(f"KO count limit exceeded: {error_msg}")
                _record_upload_metrics(
                    "upload",
                    "ko_limit_exceeded",
                    size_bytes=len(decoded),
                )
                return (
                    create_error_alert(
                        "KO Entry Limit Exceeded",
                        error_msg,
                        suggestions=[
                            f"Reduce to {settings.UPLOAD_KO_LIMIT:,} KO entries or fewer",
                            "Remove duplicate KO entries",
                            "Split into multiple files",
                        ],
                    ),
                    no_update,
                    None,  # Clear file info display on error
                )

            # ============================================================
            # STEP 9: Sanitize Sample Names
            # ============================================================
            warnings = []
            for idx, line in enumerate(lines, 1):
                if line.startswith(">"):
                    sample_name = line[1:].strip()
                    is_valid, sanitized, error = (
                        SanitizationService.sanitize_sample_name(sample_name)
                    )
                    if not is_valid:
                        logger.warning(
                            f"Invalid sample name on line {idx}: {sample_name}"
                        )
                        _record_upload_metrics(
                            "upload",
                            "sample_name_invalid",
                            size_bytes=len(decoded),
                        )
                        return (
                            create_error_alert(
                                "Invalid Sample Name",
                                f"Line {idx}: {error}",
                                suggestions=[
                                    "Use only letters, numbers, underscore (_), dash (-), and dot (.)",
                                    "Example: Sample_001, Sample-2024.v1",
                                ],
                            ),
                            no_update,
                            None,  # Clear file info display on error
                        )

                    # Log if sanitization changed the name
                    if sanitized != sample_name:
                        warnings.append(
                            f"Line {idx}: Sample name '{sample_name}' sanitized"
                        )

            # ============================================================
            # STEP 10: All Validations Passed - Store Data
            # ============================================================
            file_data = {
                "content": file_content,
                "filename": safe_filename,
                "original_filename": filename,
                "sample_count": sample_count,
                "ko_count": ko_count,
                "file_size_bytes": len(decoded),
            }

            logger.info(
                f"File upload successful: {safe_filename}",
                extra={
                    "uploaded_file": safe_filename,
                    "samples": sample_count,
                    "kos": ko_count,
                    "size_bytes": len(decoded),
                    "warnings": len(warnings),
                },
            )
            _record_upload_metrics("upload", "success", size_bytes=len(decoded))

            # ============================================================
            # STEP 11: Create File Info Display (includes success state)
            # ============================================================
            file_info = create_file_info_card(
                filename=safe_filename,
                sample_count=sample_count,
                ko_count=ko_count,
                file_size_bytes=len(decoded),
                max_samples=settings.UPLOAD_SAMPLE_LIMIT,
                max_kos=settings.UPLOAD_KO_LIMIT,
                max_size_mb=settings.UPLOAD_MAX_SIZE_MB,
                warnings=warnings if warnings else None,
            )

            # Return: no status message (deprecated), only file info card
            return no_update, file_data, file_info

        except Exception as e:
            # Generic error - log full traceback, show generic message
            logger.exception(f"Unexpected error during upload: {e}", exc_info=True)
            _record_upload_metrics("upload", "unexpected_error")
            return (
                create_error_alert(
                    "Unexpected Error",
                    "An unexpected error occurred during upload.",
                    suggestions=[
                        "Please try again",
                        "Check file format and contents",
                        "Contact support if problem persists",
                    ],
                ),
                no_update,
                None,  # Clear file info display on error
            )

    @callback(
        [
            Output("example-data-store", "data"),
            Output("upload-status", "children", allow_duplicate=True),
            Output("file-info-display", "children", allow_duplicate=True),
        ],
        Input("load-example-btn", "n_clicks"),
        prevent_initial_call=True,
    )
    @instrument_callback("upload.load_example_data")
    def load_example_data(n_clicks):
        """
        Load example dataset from file.

        Loads the pre-configured example dataset and displays file information
        with statistics about samples and KO entries.

        Parameters
        ----------
        n_clicks : int
            Number of clicks on example button

        Returns
        -------
        tuple
            (example_data, status_message, file_info)

        Notes
        -----
        Uses feedback components for consistent UI styling.
        Logs all loading events with structured context.
        """
        if n_clicks is None:
            raise PreventUpdate

        try:
            # ============================================================
            # STEP 1: Locate Example File
            # ============================================================
            example_file = (
                Path(__file__).parent.parent.parent / "data" / "exemple_dataset.txt"
            )

            if not example_file.exists():
                logger.error(
                    f"Example dataset file not found: {example_file}",
                    extra={"expected_path": str(example_file)},
                )
                _record_upload_metrics("example", "file_missing")
                return (
                    no_update,
                    create_error_alert(
                        "Example File Not Found",
                        "The example dataset file is missing from the application.",
                        suggestions=[
                            "Contact support to restore example file",
                            "Upload your own dataset instead",
                        ],
                    ),
                    None,  # Clear file info display on error
                )

            # ============================================================
            # STEP 2: Load and Parse File
            # ============================================================
            try:
                with open(example_file, "r", encoding="utf-8") as f:
                    file_content = f.read()
            except UnicodeDecodeError:
                logger.error(
                    "Example dataset encoding error",
                    extra={"file_path": str(example_file)},
                )
                _record_upload_metrics("example", "encoding_failed")
                return (
                    no_update,
                    create_error_alert(
                        "Encoding Error",
                        "Unable to read example dataset due to encoding issues.",
                        suggestions=["Contact support to fix example file encoding"],
                    ),
                    None,  # Clear file info display on error
                )

            # ============================================================
            # STEP 3: Count Samples and KOs
            # ============================================================
            lines = file_content.strip().split("\n")
            sample_count = sum(1 for line in lines if line.startswith(">"))
            ko_count = sum(1 for line in lines if line.strip().startswith("K"))

            # ============================================================
            # STEP 4: Create Data Object
            # ============================================================
            example_data = {
                "content": file_content,
                "filename": "exemple_dataset.txt",
                "sample_count": sample_count,
                "ko_count": ko_count,
                "file_size_bytes": len(file_content.encode("utf-8")),
            }

            logger.info(
                "Example dataset loaded successfully",
                extra={
                    "example_file": "exemple_dataset.txt",
                    "samples": sample_count,
                    "kos": ko_count,
                    "size_bytes": example_data["file_size_bytes"],
                },
            )
            _record_upload_metrics(
                "example",
                "success",
                size_bytes=example_data["file_size_bytes"],
            )

            # ============================================================
            # STEP 5: Create File Info Display (includes success message)
            # ============================================================
            file_info = create_file_info_card(
                filename="exemple_dataset.txt",
                sample_count=sample_count,
                ko_count=ko_count,
                file_size_bytes=example_data["file_size_bytes"],
                max_samples=settings.UPLOAD_SAMPLE_LIMIT,
                max_kos=settings.UPLOAD_KO_LIMIT,
                max_size_mb=settings.UPLOAD_MAX_SIZE_MB,
                warnings=None,
            )

            # Return: no status message (deprecated), only file info card
            return example_data, no_update, file_info

        except Exception as e:
            # Generic error - log full details, show generic message
            logger.exception("Unexpected error loading example dataset", exc_info=True)
            _record_upload_metrics("example", "unexpected_error")
            return (
                no_update,
                create_error_alert(
                    "Unexpected Error",
                    "An unexpected error occurred while loading the example dataset.",
                    suggestions=[
                        "Try again",
                        "Upload your own dataset instead",
                        "Contact support if problem persists: biorempp@gmail.com",
                    ],
                ),
                None,  # Clear file info display on error
            )

    logger.info("[OK] Real upload callbacks registered successfully")
    logger.info("  - handle_file_upload: File upload handler")
    logger.info("  - load_example_data: Example data loader")