asd
Browse files
app.py
CHANGED
@@ -328,6 +328,188 @@ def generate_paraphrases(text, setting, output_format):
|
|
328 |
|
329 |
json_output["combined_versions"] = combined_versions
|
330 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
331 |
# Classify combined versions
|
332 |
human_versions = []
|
333 |
for i, version in enumerate(combined_versions, 1):
|
@@ -336,17 +518,17 @@ def generate_paraphrases(text, setting, output_format):
|
|
336 |
formatted_output += f"Classification: {label} (confidence: {score:.2%})\n\n"
|
337 |
if label == "human-produced" or (label == "machine-generated" and score < 0.98):
|
338 |
human_versions.append((version, label, score))
|
339 |
-
|
340 |
formatted_output += "\nHuman-like or Less Confident Machine-generated versions:\n"
|
341 |
for i, (version, label, score) in enumerate(human_versions, 1):
|
342 |
formatted_output += f"Version {i}:\n{version}\n"
|
343 |
formatted_output += f"Classification: {label} (confidence: {score:.2%})\n\n"
|
344 |
-
|
345 |
json_output["human_like_versions"] = [
|
346 |
{"version": version, "label": label, "confidence_score": score}
|
347 |
for version, label, score in human_versions
|
348 |
]
|
349 |
-
|
350 |
# If no human-like versions, include the top 5 least confident machine-generated versions
|
351 |
if not human_versions:
|
352 |
human_versions = sorted([(v, l, s) for v, l, s in zip(combined_versions, [classify_text(v)[0] for v in combined_versions], [classify_text(v)[1] for v in combined_versions])], key=lambda x: x[2])[:5]
|
@@ -354,7 +536,7 @@ def generate_paraphrases(text, setting, output_format):
|
|
354 |
for i, (version, label, score) in enumerate(human_versions, 1):
|
355 |
formatted_output += f"Version {i}:\n{version}\n"
|
356 |
formatted_output += f"Classification: {label} (confidence: {score:.2%})\n\n"
|
357 |
-
|
358 |
if output_format == "text":
|
359 |
return formatted_output, "\n\n".join([v[0] for v in human_versions])
|
360 |
else:
|
|
|
328 |
|
329 |
json_output["combined_versions"] = combined_versions
|
330 |
|
331 |
+
# # Classify combined versions
|
332 |
+
# human_versions = []
|
333 |
+
# for i, version in enumerate(combined_versions, 1):
|
334 |
+
# label, score = classify_text(version)
|
335 |
+
# formatted_output += f"Version {i}:\n{version}\n"
|
336 |
+
# formatted_output += f"Classification: {label} (confidence: {score:.2%})\n\n"
|
337 |
+
# if label == "human-produced" or (label == "machine-generated" and score < 0.98):
|
338 |
+
# human_versions.append((version, label, score))
|
339 |
+
|
340 |
+
# formatted_output += "\nHuman-like or Less Confident Machine-generated versions:\n"
|
341 |
+
# for i, (version, label, score) in enumerate(human_versions, 1):
|
342 |
+
# formatted_output += f"Version {i}:\n{version}\n"
|
343 |
+
# formatted_output += f"Classification: {label} (confidence: {score:.2%})\n\n"
|
344 |
+
|
345 |
+
# json_output["human_like_versions"] = [
|
346 |
+
# {"version": version, "label": label, "confidence_score": score}
|
347 |
+
# for version, label, score in human_versions
|
348 |
+
# ]
|
349 |
+
|
350 |
+
# # If no human-like versions, include the top 5 least confident machine-generated versions
|
351 |
+
# if not human_versions:
|
352 |
+
# human_versions = sorted([(v, l, s) for v, l, s in zip(combined_versions, [classify_text(v)[0] for v in combined_versions], [classify_text(v)[1] for v in combined_versions])], key=lambda x: x[2])[:5]
|
353 |
+
# formatted_output += "\nNo human-like versions found. Showing top 5 least confident machine-generated versions:\n"
|
354 |
+
# for i, (version, label, score) in enumerate(human_versions, 1):
|
355 |
+
# formatted_output += f"Version {i}:\n{version}\n"
|
356 |
+
# formatted_output += f"Classification: {label} (confidence: {score:.2%})\n\n"
|
357 |
+
|
358 |
+
# if output_format == "text":
|
359 |
+
# return formatted_output, "\n\n".join([v[0] for v in human_versions])
|
360 |
+
# else:
|
361 |
+
# return json.dumps(json_output, indent=2), "\n\n".join([v[0] for v in human_versions])
|
362 |
+
|
363 |
+
# # Define the Gradio interface
|
364 |
+
# iface = gr.Interface(
|
365 |
+
# fn=generate_paraphrases,
|
366 |
+
# inputs=[
|
367 |
+
# gr.Textbox(lines=5, label="Input Text"),
|
368 |
+
# gr.Slider(minimum=1, maximum=5, step=1, label="Readability to Human-like Setting"),
|
369 |
+
# gr.Radio(["text", "json"], label="Output Format")
|
370 |
+
# ],
|
371 |
+
# outputs=[
|
372 |
+
# gr.Textbox(lines=20, label="Detailed Paraphrases and Classifications"),
|
373 |
+
# gr.Textbox(lines=10, label="Human-like or Less Confident Machine-generated Paraphrases")
|
374 |
+
# ],
|
375 |
+
# title="Advanced Diverse Paraphraser with Human-like Filter",
|
376 |
+
# description="Enter a text, select a setting from readable to human-like, and choose the output format to generate diverse paraphrased versions. Combined versions are classified, and those detected as human-produced or less confidently machine-generated are presented in the final output."
|
377 |
+
# )
|
378 |
+
|
379 |
+
# # Launch the interface
|
380 |
+
# iface.launch()
|
381 |
+
|
382 |
+
|
383 |
+
import os
|
384 |
+
import json
|
385 |
+
import gradio as gr
|
386 |
+
import spaces
|
387 |
+
import torch
|
388 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForSequenceClassification, T5ForConditionalGeneration
|
389 |
+
from sentence_splitter import SentenceSplitter
|
390 |
+
from itertools import product
|
391 |
+
|
392 |
+
# Get the Hugging Face token from environment variable
|
393 |
+
hf_token = os.getenv('HF_TOKEN')
|
394 |
+
|
395 |
+
cuda_available = torch.cuda.is_available()
|
396 |
+
device = torch.device("cuda" if cuda_available else "cpu")
|
397 |
+
print(f"Using device: {device}")
|
398 |
+
|
399 |
+
# Initialize paraphraser model and tokenizer
|
400 |
+
paraphraser_model_name = "NoaiGPT/777"
|
401 |
+
paraphraser_tokenizer = AutoTokenizer.from_pretrained(paraphraser_model_name, use_auth_token=hf_token)
|
402 |
+
paraphraser_model = AutoModelForSeq2SeqLM.from_pretrained(paraphraser_model_name, use_auth_token=hf_token).to(device)
|
403 |
+
|
404 |
+
# Initialize classifier model and tokenizer
|
405 |
+
classifier_model_name = "andreas122001/roberta-mixed-detector"
|
406 |
+
classifier_tokenizer = AutoTokenizer.from_pretrained(classifier_model_name)
|
407 |
+
classifier_model = AutoModelForSequenceClassification.from_pretrained(classifier_model_name).to(device)
|
408 |
+
|
409 |
+
# Initialize grammar correction model and tokenizer
|
410 |
+
grammar_model_name = "grammarly/coedit-large"
|
411 |
+
grammar_tokenizer = AutoTokenizer.from_pretrained(grammar_model_name)
|
412 |
+
grammar_model = T5ForConditionalGeneration.from_pretrained(grammar_model_name).to(device)
|
413 |
+
|
414 |
+
# Initialize sentence splitter
|
415 |
+
splitter = SentenceSplitter(language='en')
|
416 |
+
|
417 |
+
def classify_text(text):
|
418 |
+
inputs = classifier_tokenizer(text, return_tensors="pt", truncation=True, max_length=512).to(device)
|
419 |
+
with torch.no_grad():
|
420 |
+
outputs = classifier_model(**inputs)
|
421 |
+
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
422 |
+
predicted_class = torch.argmax(probabilities, dim=-1).item()
|
423 |
+
main_label = classifier_model.config.id2label[predicted_class]
|
424 |
+
main_score = probabilities[0][predicted_class].item()
|
425 |
+
return main_label, main_score
|
426 |
+
|
427 |
+
@spaces.GPU
|
428 |
+
def correct_grammar(text):
|
429 |
+
inputs = grammar_tokenizer(f'Fix grammatical errors in this sentence: {text}', return_tensors="pt").input_ids.to(device)
|
430 |
+
outputs = grammar_model.generate(inputs, max_length=256)
|
431 |
+
corrected_text = grammar_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
432 |
+
return corrected_text
|
433 |
+
|
434 |
+
@spaces.GPU
|
435 |
+
def generate_paraphrases(text, setting, output_format):
|
436 |
+
sentences = splitter.split(text)
|
437 |
+
all_sentence_paraphrases = []
|
438 |
+
|
439 |
+
# Define settings
|
440 |
+
settings = {
|
441 |
+
1: {"num_return_sequences": 2, "repetition_penalty": 1.1, "no_repeat_ngram_size": 2, "temperature": 1.0, "max_length": 128},
|
442 |
+
2: {"num_return_sequences": 2, "repetition_penalty": 1.2, "no_repeat_ngram_size": 3, "temperature": 1.2, "max_length": 192},
|
443 |
+
3: {"num_return_sequences": 2, "repetition_penalty": 1.3, "no_repeat_ngram_size": 4, "temperature": 1.4, "max_length": 256},
|
444 |
+
4: {"num_return_sequences": 2, "repetition_penalty": 1.4, "no_repeat_ngram_size": 5, "temperature": 1.6, "max_length": 320},
|
445 |
+
5: {"num_return_sequences": 2, "repetition_penalty": 1.5, "no_repeat_ngram_size": 6, "temperature": 1.8, "max_length": 384}
|
446 |
+
}
|
447 |
+
config = settings.get(setting, settings[5])
|
448 |
+
|
449 |
+
top_k = 50
|
450 |
+
top_p = 0.95
|
451 |
+
length_penalty = 1.0
|
452 |
+
|
453 |
+
formatted_output = "Original text:\n" + text + "\n\n"
|
454 |
+
formatted_output += "Paraphrased versions:\n"
|
455 |
+
|
456 |
+
json_output = {
|
457 |
+
"original_text": text,
|
458 |
+
"paraphrased_versions": [],
|
459 |
+
"combined_versions": [],
|
460 |
+
"human_like_versions": []
|
461 |
+
}
|
462 |
+
|
463 |
+
# Process sentences in batches
|
464 |
+
batch_size = 4
|
465 |
+
for i in range(0, len(sentences), batch_size):
|
466 |
+
batch_sentences = sentences[i:i + batch_size]
|
467 |
+
inputs = paraphraser_tokenizer([f'paraphraser: {sentence}' for sentence in batch_sentences], return_tensors="pt", padding="longest", truncation=True, max_length=config["max_length"]).to(device)
|
468 |
+
|
469 |
+
# Generate paraphrases using the specified parameters
|
470 |
+
outputs = paraphraser_model.generate(
|
471 |
+
inputs.input_ids,
|
472 |
+
attention_mask=inputs.attention_mask,
|
473 |
+
num_return_sequences=config["num_return_sequences"],
|
474 |
+
repetition_penalty=config["repetition_penalty"],
|
475 |
+
no_repeat_ngram_size=config["no_repeat_ngram_size"],
|
476 |
+
temperature=config["temperature"],
|
477 |
+
max_length=config["max_length"],
|
478 |
+
top_k=top_k,
|
479 |
+
top_p=top_p,
|
480 |
+
do_sample=True,
|
481 |
+
early_stopping=False,
|
482 |
+
length_penalty=length_penalty
|
483 |
+
)
|
484 |
+
|
485 |
+
paraphrases = paraphraser_tokenizer.batch_decode(outputs, skip_special_tokens=True)
|
486 |
+
|
487 |
+
corrected_paraphrases = [correct_grammar(paraphrase) for paraphrase in paraphrases]
|
488 |
+
|
489 |
+
for j, sentence in enumerate(batch_sentences):
|
490 |
+
formatted_output += f"Original sentence {i + j + 1}: {sentence}\n"
|
491 |
+
sentence_paraphrases = corrected_paraphrases[j * config["num_return_sequences"]:(j + 1) * config["num_return_sequences"]]
|
492 |
+
for k, paraphrase in enumerate(sentence_paraphrases, 1):
|
493 |
+
formatted_output += f" Paraphrase {k}: {paraphrase}\n"
|
494 |
+
|
495 |
+
json_output["paraphrased_versions"].append({
|
496 |
+
f"original_sentence_{i + j + 1}": sentence,
|
497 |
+
"paraphrases": sentence_paraphrases
|
498 |
+
})
|
499 |
+
|
500 |
+
all_sentence_paraphrases.append(sentence_paraphrases)
|
501 |
+
formatted_output += "\n"
|
502 |
+
|
503 |
+
all_combinations = list(product(*all_sentence_paraphrases))
|
504 |
+
|
505 |
+
formatted_output += "\nCombined paraphrased versions:\n"
|
506 |
+
combined_versions = []
|
507 |
+
for i, combination in enumerate(all_combinations[:50], 1): # Limit to 50 combinations
|
508 |
+
combined_paraphrase = " ".join(combination)
|
509 |
+
combined_versions.append(combined_paraphrase)
|
510 |
+
|
511 |
+
json_output["combined_versions"] = combined_versions
|
512 |
+
|
513 |
# Classify combined versions
|
514 |
human_versions = []
|
515 |
for i, version in enumerate(combined_versions, 1):
|
|
|
518 |
formatted_output += f"Classification: {label} (confidence: {score:.2%})\n\n"
|
519 |
if label == "human-produced" or (label == "machine-generated" and score < 0.98):
|
520 |
human_versions.append((version, label, score))
|
521 |
+
|
522 |
formatted_output += "\nHuman-like or Less Confident Machine-generated versions:\n"
|
523 |
for i, (version, label, score) in enumerate(human_versions, 1):
|
524 |
formatted_output += f"Version {i}:\n{version}\n"
|
525 |
formatted_output += f"Classification: {label} (confidence: {score:.2%})\n\n"
|
526 |
+
|
527 |
json_output["human_like_versions"] = [
|
528 |
{"version": version, "label": label, "confidence_score": score}
|
529 |
for version, label, score in human_versions
|
530 |
]
|
531 |
+
|
532 |
# If no human-like versions, include the top 5 least confident machine-generated versions
|
533 |
if not human_versions:
|
534 |
human_versions = sorted([(v, l, s) for v, l, s in zip(combined_versions, [classify_text(v)[0] for v in combined_versions], [classify_text(v)[1] for v in combined_versions])], key=lambda x: x[2])[:5]
|
|
|
536 |
for i, (version, label, score) in enumerate(human_versions, 1):
|
537 |
formatted_output += f"Version {i}:\n{version}\n"
|
538 |
formatted_output += f"Classification: {label} (confidence: {score:.2%})\n\n"
|
539 |
+
|
540 |
if output_format == "text":
|
541 |
return formatted_output, "\n\n".join([v[0] for v in human_versions])
|
542 |
else:
|