Spaces:
Sleeping

File size: 4,693 Bytes
5f311a8
6f6dfff
 
e97478e
6f6dfff
e97478e
5f311a8
6f6dfff
e97478e
6f6dfff
 
e97478e
6f6dfff
 
e97478e
 
6f6dfff
 
 
 
e97478e
 
6f6dfff
 
e97478e
 
 
 
 
 
 
 
 
 
 
 
 
6f6dfff
7253ddc
e97478e
7253ddc
e97478e
5f311a8
e97478e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7253ddc
6f6dfff
7253ddc
e97478e
7253ddc
 
 
e97478e
7253ddc
 
e97478e
7253ddc
e97478e
7253ddc
 
e97478e
7253ddc
 
 
 
e97478e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f6dfff
 
 
e97478e
6f6dfff
 
 
5f311a8
 
 
6f6dfff
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, request, jsonify, make_response
from flask_cors import CORS
import torch
from transformers import MarianMTModel, MarianTokenizer
import nltk
from nltk.corpus import wordnet
import random

# Download necessary data
try:
    nltk.data.find('tokenizers/punkt')
    nltk.data.find('corpora/wordnet')
except LookupError:
    nltk.download('punkt')
    nltk.download('wordnet')
    nltk.download('omw-1.4')

app = Flask(__name__)
CORS(app)

# --- LOAD TRANSLATION MODELS (The "Laundromat") ---
# We use German (de) as the middle language because it changes sentence structure significantly.
device = "cuda" if torch.cuda.is_available() else "cpu"

print("Loading Translation Models... This takes 1 minute.")

# Model 1: English to German
model_name_en_de = "Helsinki-NLP/opus-mt-en-de"
tokenizer_en_de = MarianTokenizer.from_pretrained(model_name_en_de)
model_en_de = MarianMTModel.from_pretrained(model_name_en_de).to(device)

# Model 2: German to English
model_name_de_en = "Helsinki-NLP/opus-mt-de-en"
tokenizer_de_en = MarianTokenizer.from_pretrained(model_name_de_en)
model_de_en = MarianMTModel.from_pretrained(model_name_de_en).to(device)

print("Models Loaded! Ready to Launder text.")

def is_heading(text):
    """Detects headings to avoid messing them up."""
    text = text.strip()
    if len(text) < 3 or len(text) > 80: return False
    if text.endswith(('.', '!', '?')): return False
    return text.istitle() or text.isupper()

def synonym_swap(text):
    """Adds a sprinkle of randomness/errors that detectors love."""
    words = text.split()
    new_words = []
    for word in words:
        # 15% chance to swap a word (Low enough to be readable, high enough to fool AI)
        if len(word) > 4 and random.random() < 0.15:
            synonyms = wordnet.synsets(word)
            if synonyms:
                lemmas = [l.name().replace('_', ' ') for s in synonyms for l in s.lemmas()]
                # Pick a random synonym that isn't the same word
                candidates = [l for l in lemmas if l.lower() != word.lower()]
                if candidates:
                    word = random.choice(candidates)
        new_words.append(word)
    return " ".join(new_words)

def back_translate(text):
    """Runs text through the washing machine (En -> De -> En)."""
    # 1. English -> German
    inputs = tokenizer_en_de(text, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device)
    translated = model_en_de.generate(**inputs, max_length=512)
    german_text = tokenizer_en_de.batch_decode(translated, skip_special_tokens=True)[0]

    # 2. German -> English
    inputs = tokenizer_de_en(german_text, return_tensors="pt", padding=True, truncation=True, max_length=512).to(device)
    back_translated = model_de_en.generate(**inputs, max_length=512)
    english_text = tokenizer_de_en.batch_decode(back_translated, skip_special_tokens=True)[0]

    return english_text

def humanise_text(text):
    paragraphs = text.split('\n')
    final_paragraphs = []

    for paragraph in paragraphs:
        if not paragraph.strip():
            final_paragraphs.append("")
            continue

        # Skip Headings
        if is_heading(paragraph):
            final_paragraphs.append(paragraph)
            continue

        # Split into sentences to handle long text
        sentences = nltk.sent_tokenize(paragraph)
        new_sentences = []

        for sentence in sentences:
            try:
                # Step 1: Back Translate (Rewrite Structure)
                laundered = back_translate(sentence)
                
                # Step 2: Light Synonym Swap (Add Randomness)
                final_sent = synonym_swap(laundered)
                
                new_sentences.append(final_sent)
            except Exception as e:
                print(f"Error processing sentence: {e}")
                new_sentences.append(sentence) # Fallback to original

        final_paragraphs.append(" ".join(new_sentences))

    return "\n".join(final_paragraphs)

@app.route("/", methods=["GET"])
def home():
    return "Humanizer (Back-Translation Edition) is Running!"

@app.route("/api/humanise", methods=["POST"])
def humanise():
    response = make_response()
    response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
    
    data = request.get_json()
    text = data.get("text", "")
    
    if not text.strip():
        return jsonify({"humanisedText": ""})

    try:
        result = humanise_text(text)
        return jsonify({"humanisedText": result})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)