backend / simplify.py
Mudiji's picture
Upload 14 files
d15459a verified
Raw History Blame Contribute Delete
3.64 kB
import torch
from transformers import T5Tokenizer, T5ForConditionalGeneration
# --- 1. SETUP: Load your model (run this once) ---
# !! IMPORTANT !!
# Change this path to the folder where your best model is saved.
# (e.g., "./my_final_simplifier_model_v3" or "/content/drive/MyDrive/my_final_simplifier_model_v3")
MODEL_PATH = r"C:\Users\kunal\Documents\Web dev\Text-Simplication\my_final_simplifier_model_v3"
print("Loading model... This may take a moment.")
# Check for your RTX 3050 GPU
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
# Load the tokenizer and model
try:
tokenizer = T5Tokenizer.from_pretrained(MODEL_PATH)
model = T5ForConditionalGeneration.from_pretrained(MODEL_PATH).to(device)
model.eval() # Set the model to evaluation mode (important!)
print(f"Model successfully loaded from {MODEL_PATH}")
except Exception as e:
print(f"--- ❌ ERROR LOADING MODEL ---")
print(f"Error: {e}")
print(f"Please make sure the path '{MODEL_PATH}' is correct and contains the model files.")
# If the model didn't load, we can't continue.
exit()
# --- 2. The Simplification Function ---
def simplify_text(text: str) -> str:
"""
Takes a complex text string and returns the simplified version
using the loaded T5 model.
"""
# The T5 model needs this prefix to know what task to do
input_text = "simplify: " + text
# Tokenize the input text
inputs = tokenizer(
input_text,
return_tensors="pt",
max_length=256, # Max length the model saw during training
truncation=True
).to(device) # Move the input data to the GPU
# Generate the simplified output
outputs = model.generate(
inputs['input_ids']
max_length=128, # Max length for the output
num_beams=4, # Use beam search for higher quality results
early_stopping=True # Stop when the best beam is found
)
# Decode the output tokens back into a string
simplified_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
return simplified_text
# --- 3. EXAMPLE USAGE ---
print("\n--- Running Simplification Examples ---")
# The sentence that your last model failed to simplify (words)
complex_example_1 = "The magnanimous philanthropist decided to utilize his fortune to construct a new facility, and everyone was overjoyed."
# The sentence that your last model DID simplify (splitting)
complex_example_2 = "Jeddah is the principal gateway to Mecca, Islam's holiest city, which able-bodied Muslims are required to visit at least once in their lifetime."
# A new simple sentence (to check it doesn't break it)
simple_example = "The dog, which was brown, ran away."
print(f"\nOriginal:\n{complex_example_1}")
simplified_1 = simplify_text(complex_example_1)
print(f"\nSimplified:\n{simplified_1}")
print(f"\nOriginal:\n{complex_example_2}")
simplified_2 = simplify_text(complex_example_2)
print(f"\nSimplified:\n{simplified_2}")
print(f"\nOriginal:\n{simple_example}")
simplified_3 = simplify_text(simple_example)
print(f"\nSimplified:\n{simplified_3}")
# --- 4. Interactive Mode ---
print("\n--- 🤖 Interactive Simplifier ---")
print("Enter 'q' or 'quit' to stop.")
while True:
text_to_simplify = input("\nEnter text to simplify: ")
if text_to_simplify.lower() in ['q', 'quit']:
break
simplified_output = simplify_text(text_to_simplify)
print(f"\nSimplified:\n{simplified_output}")
print("Done. Exiting.")