File size: 2,373 Bytes
85ba912
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Validation and gentle editing layer for generated copy.

This module:
- Applies banned-term replacements (e.g., "guaranteed" -> "aim to").
- Trims text to platform character cap.
- Returns an audit log of what changed.
"""

from typing import List, Dict, Tuple

from .platform_rules import PlatformConfig


# Soft language map: you can expand this list as you like
BANNED_MAP = {
    "guaranteed": "aim to",
    "guarantee": "aim to",
    "no risk": "low risk",
}


def _apply_banned_terms(text: str) -> Tuple[str, List[Dict]]:
    """Replace banned phrases and record changes."""
    audit: List[Dict] = []
    cleaned = text

    for bad, replacement in BANNED_MAP.items():
        if bad.lower() in cleaned.lower():
            before = cleaned
            # simple case-insensitive replace
            cleaned = cleaned.replace(bad, replacement)
            cleaned = cleaned.replace(bad.capitalize(), replacement)
            cleaned = cleaned.replace(bad.upper(), replacement.upper())
            audit.append(
                {
                    "rule": "banned_term",
                    "bad": bad,
                    "replacement": replacement,
                }
            )

    return cleaned, audit


def _apply_length_cap(text: str, platform: PlatformConfig) -> Tuple[str, List[Dict]]:
    """Trim text to the platform's character cap if necessary."""
    audit: List[Dict] = []
    cap = platform.char_cap

    if len(text) > cap:
        before_len = len(text)
        trimmed = text[:cap].rstrip()
        audit.append(
            {
                "rule": "length_trim",
                "before_len": before_len,
                "after_len": len(trimmed),
                "cap": cap,
            }
        )
        return trimmed, audit

    return text, audit


def validate_and_edit(
    text: str,
    platform: PlatformConfig,
) -> Tuple[str, List[Dict]]:
    """
    Apply all validators in order and collect a combined audit log.

    Returns:
        final_text, audit_log
    """
    audit_log: List[Dict] = []

    # 1) banned terms
    text, banned_audit = _apply_banned_terms(text)
    audit_log.extend(banned_audit)

    # 2) length trim
    text, trim_audit = _apply_length_cap(text, platform)
    audit_log.extend(trim_audit)

    # (you can add more steps later: CTA normalization, emoji limits, etc.)
    return text, audit_log