Spaces:
Runtime error
Runtime error
import gradio as gr | |
import torch | |
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForSequenceClassification | |
from transformers.pipelines import pipeline | |
from sentence_transformers import SentenceTransformer, util | |
import numpy as np | |
import gradio.themes as grthemes | |
# Paraphrasing model: tuner007/pegasus_paraphrase | |
PARAPHRASE_MODEL_NAME = "tuner007/pegasus_paraphrase" | |
paraphrase_tokenizer = AutoTokenizer.from_pretrained(PARAPHRASE_MODEL_NAME) | |
paraphrase_model = AutoModelForSeq2SeqLM.from_pretrained(PARAPHRASE_MODEL_NAME) | |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
paraphrase_model = paraphrase_model.to(device) | |
# AI Detector: desklib/ai-text-detector-v1.01 | |
AI_DETECTOR_MODEL = "desklib/ai-text-detector-v1.01" | |
ai_detector = pipeline("text-classification", model=AI_DETECTOR_MODEL, device=0 if torch.cuda.is_available() else -1) | |
# Semantic similarity model | |
similarity_model = SentenceTransformer('all-MiniLM-L6-v2') | |
def paraphrase(text): | |
prompt = text.strip() | |
batch = paraphrase_tokenizer([prompt], truncation=True, padding='longest', max_length=60, return_tensors="pt").to(device) | |
translated = paraphrase_model.generate( | |
**batch, | |
max_length=60, | |
num_beams=5, | |
num_return_sequences=1, | |
temperature=1.0 | |
) | |
tgt_text = paraphrase_tokenizer.batch_decode(translated, skip_special_tokens=True) | |
return tgt_text[0] if tgt_text else "" | |
def semantic_similarity(text1, text2): | |
emb1 = similarity_model.encode(text1, convert_to_tensor=True) | |
emb2 = similarity_model.encode(text2, convert_to_tensor=True) | |
sim = util.pytorch_cos_sim(emb1, emb2).item() | |
return sim | |
def ai_detect(text): | |
# Returns probability of being AI-generated (label 'LABEL_1' = AI, 'LABEL_0' = Human) | |
result = ai_detector(text) | |
for r in result: | |
if r['label'] in ['LABEL_1', 'Fake']: | |
return r['score'] | |
elif r['label'] in ['LABEL_0', 'Real']: | |
return 1.0 - r['score'] | |
return 0.5 # fallback | |
def humanization_score(sim, ai_prob): | |
# Lower similarity and lower AI probability = more human | |
score = (1.0 - sim) * 0.5 + (1.0 - ai_prob) * 0.5 | |
return score | |
def humanization_rating(score): | |
if score < 0.7: | |
return f"β οΈ Still robotic ({score:.2f})" | |
elif score < 0.85: | |
return f"π Acceptable ({score:.2f})" | |
else: | |
return f"β Highly Human ({score:.2f})" | |
def process(text, tone): | |
if not text.strip(): | |
return "", "", 0.0, "", 0.0 | |
# Pre-humanization AI detection | |
pre_ai_prob = ai_detect(text) | |
# Paraphrase | |
try: | |
paraphrased = paraphrase(text) | |
except Exception as e: | |
return "[Error in paraphrasing: {}]".format(str(e)), "", 0.0, "", 0.0 | |
# Post-humanization AI detection | |
post_ai_prob = ai_detect(paraphrased) | |
# Semantic similarity | |
sim = semantic_similarity(text, paraphrased) | |
# Humanization score | |
score = humanization_score(sim, post_ai_prob) | |
rating = humanization_rating(score) | |
ai_score_str = f"Pre: {pre_ai_prob*100:.1f}% | Post: {post_ai_prob*100:.1f}%" | |
return ( | |
paraphrased, # gr.Textbox (string) | |
ai_score_str, # gr.Markdown (string) | |
sim, # gr.Number (float) | |
rating, # gr.Markdown (string) | |
score * 100 # gr.Number (float) | |
) | |
# Custom dark theme using gradio.themes.Base | |
custom_theme = grthemes.Base( | |
primary_hue="blue", | |
secondary_hue="blue", | |
neutral_hue="slate" | |
) | |
with gr.Blocks(theme=custom_theme) as demo: | |
gr.Markdown(""" | |
# π§ AI Humanizer | |
<div style='display:flex;justify-content:space-between;align-items:center;'> | |
<span style='font-size:1.2em;color:#7bb1ff;'>Rewrite AI text to sound 100% human</span> | |
<span style='font-weight:bold;color:#7bb1ff;'>Made by Taha</span> | |
</div> | |
""", elem_id="header") | |
with gr.Row(): | |
with gr.Column(): | |
text_in = gr.Textbox(label="Paste AI-generated text here", lines=8, placeholder="Paste your text...") | |
tone = gr.Radio(["Academic", "Casual", "Friendly", "Stealth"], value="Stealth", label="Tone Selector") | |
btn = gr.Button("Humanize", elem_id="humanize-btn") | |
with gr.Column(): | |
text_out = gr.Textbox(label="Humanized Output", lines=8, interactive=False) | |
ai_scores = gr.Markdown("", elem_id="ai-scores") | |
sim_score = gr.Number(label="Similarity (0=very different, 1=very similar)", interactive=False) | |
rating = gr.Markdown("", elem_id="rating") | |
human_score = gr.Number(label="Humanization Score (%)", interactive=False) | |
btn.click( | |
process, | |
inputs=[text_in, tone], | |
outputs=[text_out, ai_scores, sim_score, rating, human_score], | |
api_name="humanize" | |
) | |
gr.Markdown(""" | |
<div style='text-align:center;color:#7bb1ff;margin-top:2em;'> | |
<b>Made by Taha</b> | Free for unlimited use | Optimized for students | |
</div> | |
""", elem_id="footer") | |
demo.launch() |