Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345675 unmodified lines131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960617 unmodified lines697071727374from flask import Flask, request, jsonifyfrom flask_cors import CORSimport torchfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLMimport nltk# Download sentence splitter5 unmodified linesapp = Flask(__name__)CORS(app)# --- 1. NEW MODEL (Better for humanizing) ---MODEL_NAME = "humarin/chatgpt_paraphraser_on_T5_base"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)print("Model loaded successfully!")def humanise_text(text):sentences = nltk.sent_tokenize(text)humanised_sentences = []for sentence in sentences:# Prepare input for the modelinput_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 randomnesstemperature=1.2, # HIGHER TEMP = More "Human/Creative" (Risky)top_k=60, # Lower top_k forces it to consider rare wordstop_p=0.90, # Slightly tighter probability spreadrepetition_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)@app.route("/", methods=["GET"])def home():return "Humanizer API is Running! Use /api/humanise endpoint."@app.route("/api/humanise", methods=["POST"])def humanise():7 unmodified linesresult = humanise_text(text)return jsonify({"humanisedText": result})except Exception as e:return jsonify({"error": str(e)}), 500if __name__ == "__main__":12345675 unmodified lines131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990917 unmodified lines99100101102103104105from flask import Flask, request, jsonifyfrom flask_cors import CORSimport torchfrom transformers import PegasusForConditionalGeneration, PegasusTokenizerimport nltk# Download sentence splitter5 unmodified linesapp = Flask(__name__)CORS(app)# --- 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 = 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 linesif len(text) > 80: return False # Too long to be a headingif text[-1] in ['.', '!', '?']: return False # Headings don't usually have punctuationreturn True # It's probably a heading!def humanise_text(text):# 1. Split by PARAGRAPHS first (Double newline) to preserve structureparagraphs = text.split('\n')humanised_paragraphs = []for paragraph in paragraphs:# If empty line, keep it to preserve spacingif 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 textsentences = nltk.sent_tokenize(paragraph)new_sentences = []for sentence in sentences:# Skip tiny fragmentsif 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 wordstranslated = 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 newlinesreturn "\n".join(humanised_paragraphs)@app.route("/", methods=["GET"])def home():return "Humanizer API is Running (Pegasus Engine)! Use /api/humanise endpoint."@app.route("/api/humanise", methods=["POST"])def humanise():7 unmodified linesresult = humanise_text(text)return jsonify({"humanisedText": result})except Exception as e:print(f"Error: {e}")return jsonify({"error": str(e)}), 500if __name__ == "__main__":
app.py+66-35