Spaces:
Sleeping
Sleeping
Update app.py
Browse files123445675 unmodified lines13141516171617181920212122222324252627282930313233343536372627282930313233343536373839404142434445464748495051525354383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868758888990917 unmodified lines99100101102103104105from flask import Flask, request, jsonifyfrom flask_cors import CORSimport torchfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLMfrom transformers import PegasusForConditionalGeneration, PegasusTokenizerimport nltk
# Download sentence splitter5 unmodified linesapp = Flask(__name__)CORS(app)
# --- 1. NEW MODEL (Better for humanizing) ---MODEL_NAME = "humarin/chatgpt_paraphraser_on_T5_base"# --- 1. NEW MODEL: PEGASUS (Better for Human-like flow) ---# This model is different from T5 and often bypasses detectors better.MODEL_NAME = "tuner007/pegasus_paraphrase"device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Loading AI Model: {MODEL_NAME} on {device}...")tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME).to(device)tokenizer = PegasusTokenizer.from_pretrained(MODEL_NAME)model = PegasusForConditionalGeneration.from_pretrained(MODEL_NAME).to(device)print("Model loaded successfully!")
def is_heading(text): """ Detects if a line is likely a heading/title. Headings are usually short (under 60 chars) and don't end with . or ! or ? """ text = text.strip() if len(text) < 2: return False # Ignore empty/tiny lines if len(text) > 80: return False # Too long to be a heading if text[-1] in ['.', '!', '?']: return False # Headings don't usually have punctuation return True # It's probably a heading!
def humanise_text(text): sentences = nltk.sent_tokenize(text) humanised_sentences = []
for sentence in sentences: # Prepare input for the model input_text = "paraphrase: " + sentence + " </s>" encoding = tokenizer.encode_plus(input_text, padding="longest", return_tensors="pt") input_ids = encoding["input_ids"].to(device) attention_masks = encoding["attention_mask"].to(device)
# --- 2. ANTI-DETECTION SETTINGS (The Secret Sauce) --- outputs = model.generate( input_ids=input_ids, attention_mask=attention_masks, max_length=256, do_sample=True, # Enable randomness temperature=1.2, # HIGHER TEMP = More "Human/Creative" (Risky) top_k=60, # Lower top_k forces it to consider rare words top_p=0.90, # Slightly tighter probability spread repetition_penalty=1.3, # Force it to NOT repeat words (Humans don't repeat) early_stopping=True, num_return_sequences=1 ) line = tokenizer.decode(outputs[0], skip_special_tokens=True, clean_up_tokenization_spaces=True) humanised_sentences.append(line)
return " ".join(humanised_sentences) # 1. Split by PARAGRAPHS first (Double newline) to preserve structure paragraphs = text.split('\n') humanised_paragraphs = []
for paragraph in paragraphs: # If empty line, keep it to preserve spacing if not paragraph.strip(): humanised_paragraphs.append("") continue
# 2. HEADER PROTECTION: If it looks like a heading, DON'T touch it. if is_heading(paragraph): humanised_paragraphs.append(paragraph) continue
# 3. Process normal text sentences = nltk.sent_tokenize(paragraph) new_sentences = []
for sentence in sentences: # Skip tiny fragments if len(sentence) < 5: new_sentences.append(sentence) continue
# Prepare input (Pegasus doesn't need 'paraphrase:' prefix) batch = tokenizer([sentence], truncation=True, padding='longest', max_length=60, return_tensors="pt").to(device) # --- CHAOS SETTINGS --- # temperature=1.3 makes it risky/creative (Humans are risky) # top_k=50 forces it to pick from a wider pool of words translated = model.generate( **batch, max_length=60, num_beams=10, num_return_sequences=1, temperature=1.3, repetition_penalty=1.5 # Crucial: stops it from repeating robotic patterns ) tgt_text = tokenizer.batch_decode(translated, skip_special_tokens=True) new_sentences.append(tgt_text[0])
humanised_paragraphs.append(" ".join(new_sentences))
# Join back with original newlines return "\n".join(humanised_paragraphs)
@app.route("/", methods=["GET"])def home(): return "Humanizer API is Running! Use /api/humanise endpoint." return "Humanizer API is Running (Pegasus Engine)! Use /api/humanise endpoint."
@app.route("/api/humanise", methods=["POST"])def humanise():7 unmodified lines result = humanise_text(text) return jsonify({"humanisedText": result}) except Exception as e: print(f"Error: {e}") return jsonify({"error": str(e)}), 500
if __name__ == "__main__":app.py+66-35