import json import streamlit as st from pyodide.code import run_js from pyodide.ffi import to_js from js import JSON, Object # ONNX (browser) copy of google/flan-t5-small - T5 text-to-text model MODEL = "Xenova/flan-t5-small" st.set_page_config(page_title="AI Paraphraser", page_icon="✨", layout="wide") # MANDATORY: Name and Student ID in the title st.title("Amna Shahzad - Student ID: B04-0923-000008") st.caption("CS4106 Mid-Term | AI Paraphraser (Text-to-Text with T5)") if "gen" not in st.session_state: msg = st.empty() msg.info("Loading T5 model (first run only, please wait)...") try: mod = await run_js("import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1')") st.session_state["gen"] = await mod.pipeline("text2text-generation", MODEL) msg.empty() except Exception as e: msg.error(f"Could not load model: {e}") st.stop() gen = st.session_state["gen"] st.success(f"Model loaded: {MODEL}") text = st.text_area("Enter a sentence to paraphrase:", height=120, max_chars=1000) creativity = st.slider("Creativity (temperature)", 0.3, 1.5, 0.8) if st.button("Paraphrase"): if not text.strip(): st.warning("Please type something first.") elif len(text.split()) > 150: st.error("Text too long - please keep it under 150 words.") else: try: with st.spinner("Paraphrasing..."): prompt = "Paraphrase this sentence in different words: " + text opts = to_js({"max_new_tokens": 128, "do_sample": True, "temperature": creativity, "top_p": 0.9}, dict_converter=Object.fromEntries) raw = await gen(prompt, opts) output = json.loads(JSON.stringify(raw))[0]["generated_text"] col1, col2 = st.columns(2) with col1: st.subheader("📝 Original") st.info(text) st.caption(f"{len(text.split())} words") with col2: st.subheader("✨ Paraphrased") st.success(output) st.caption(f"{len(output.split())} words") if output.strip().lower() == text.strip().lower(): st.warning("⚠️ Output is identical to input - try again or raise creativity.") except Exception as e: st.error(f"Something went wrong: {e}")