Spaces:
Running on Zero

File size: 2,211 Bytes
bf8c887
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f2d2d6
bf8c887
 
 
 
7f2d2d6
 
 
 
 
 
 
bf8c887
 
7f2d2d6
 
 
 
 
 
 
bf8c887
 
 
 
 
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
from pathlib import Path
from typing import Tuple

class FileValidationError(Exception):
    pass

def validate_resume_file(file_path: Path | str, max_size_mb: int = 15) -> Tuple[bool, str]:
    """
    Validates resume file path, existence, size, and header signature.
    Returns (is_valid, error_message).
    """
    path = Path(file_path)
    if not path.exists():
        return False, f"File does not exist: {path}"
    
    if not path.is_file():
        return False, f"Path is not a regular file: {path}"
        
    size_mb = path.stat().st_size / (1024 * 1024)
    if size_mb == 0:
        return False, "File is empty (0 bytes)"
        
    if size_mb > max_size_mb:
        return False, f"File size ({size_mb:.2f} MB) exceeds maximum limit of {max_size_mb} MB"
        
    suffix = path.suffix.lower()
    if suffix not in (".pdf", ".docx", ".txt"):
        return False, f"Unsupported file extension: {suffix}. Supported: .pdf, .docx, .txt"
        
    # Check magic bytes (with safe fallback for pre-extracted text streams from MCP read_file)
    try:
        with open(path, "rb") as f:
            header = f.read(8)
            if suffix == ".pdf" and not header.startswith(b"%PDF"):
                try:
                    with open(path, "r", encoding="utf-8", errors="strict") as tf:
                        first_chars = tf.read(100)
                        if len(first_chars.strip()) > 10:
                            return True, ""
                except Exception:
                    pass
                return False, "Invalid PDF header signature (corrupted or renamed file)"
            elif suffix == ".docx" and not header.startswith(b"PK\x03\x04"):
                try:
                    with open(path, "r", encoding="utf-8", errors="strict") as tf:
                        first_chars = tf.read(100)
                        if len(first_chars.strip()) > 10:
                            return True, ""
                except Exception:
                    pass
                return False, "Invalid DOCX header signature (not a valid zip package)"
    except Exception as e:
        return False, f"Error reading file header: {str(e)}"
        
    return True, ""