Spaces:
Sleeping
Sleeping
Download app.py from makadev/humanizer-api: direct link, hf CLI and curl.
- Browser
- Download file 4.69 kB
-
https://huggingface.co/spaces/makadev/humanizer-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/makadev/humanizer-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/makadev/humanizer-api/resolve/main/app.py
4.69 kB
| 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) | |
| def home(): | |
| return "Humanizer (Back-Translation Edition) is Running!" | |
| 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) |