Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376import { useState, useRef, useCallback } from "react";const CONTENT = `Text generation is the task of producing natural language text given an input prompt. It is commonly used for chatbots, creative writing, summarization, and code generation.Most modern text generation models are based on the transformer architecture and are trained using next-token prediction. The transformer uses self-attention mechanisms to weigh the importance of different words in a sequence when making predictions.During inference, the model repeatedly samples the most likely next token until a stopping condition is reached. This process is called autoregressive generation. Parameters like temperature and top-p sampling control the randomness and diversity of the output.Large language models (LLMs) like GPT-4, Claude, and Llama are trained on vast corpora of text from the internet, books, and other sources. This gives them broad world knowledge and language understanding.Instruction-tuned models are further trained to follow user instructions, using techniques like supervised fine-tuning (SFT) and reinforcement learning from human feedback (RLHF). This makes them much more useful as assistants compared to base language models.`;const PARAGRAPHS = CONTENT.split("\n\n");export default function App() {const [segments, setSegments] = useState(() =>PARAGRAPHS.map((text, i) => ({id: i,parts: [{ type: "text", content: text }],})));const [selection, setSelection] = useState(null);const [loading, setLoading] = useState(false);const [buttonPos, setButtonPos] = useState(null);const contentRef = useRef(null);const handleMouseUp = useCallback(() => {const sel = window.getSelection();if (!sel || sel.isCollapsed) {setSelection(null);setButtonPos(null);return;}const text = sel.toString().trim();if (!text || text.length < 3) {setSelection(null);setButtonPos(null);return;}// Find which paragraph this belongs tolet paraIndex = -1;let node = sel.anchorNode;while (node && node !== contentRef.current) {if (node.dataset && node.dataset.para !== undefined) {paraIndex = parseInt(node.dataset.para);break;}node = node.parentNode;}if (paraIndex === -1) {setSelection(null);setButtonPos(null);return;}const range = sel.getRangeAt(0);const rect = range.getBoundingClientRect();const containerRect = contentRef.current.getBoundingClientRect();setSelection({ text, paraIndex });setButtonPos({top: rect.bottom - containerRect.top + 8,left: Math.min(rect.left - containerRect.left,containerRect.width - 160),});}, []);const handleExplain = async () => {if (!selection || loading) return;const { text, paraIndex } = selection;setLoading(true);setButtonPos(null);try {const response = await fetch("https://api.anthropic.com/v1/messages", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({model: "claude-sonnet-4-20250514",max_tokens: 1000,messages: [{role: "user",content: `You are an ML instructor. A student highlighted this text from a learning resource and wants a clear, concise explanation (2-4 sentences, no fluff):\n\n"${text}"\n\nExplain it simply and intuitively.`,},],}),});const data = await response.json();const explanation = data.content?.[0]?.text || "Could not generate explanation.";// Replace the selected text in the paragraph with [original, explanation]setSegments((prev) =>prev.map((para) => {if (para.id !== paraIndex) return para;const newParts = [];for (const part of para.parts) {if (part.type !== "text") {newParts.push(part);continue;}const idx = part.content.indexOf(text);if (idx === -1) {newParts.push(part);continue;}if (idx > 0) newParts.push({ type: "text", content: part.content.slice(0, idx) });newParts.push({ type: "explained", original: text, explanation });const after = part.content.slice(idx + text.length);if (after) newParts.push({ type: "text", content: after });}return { ...para, parts: newParts };}));} catch (e) {console.error(e);}setSelection(null);setLoading(false);window.getSelection()?.removeAllRanges();};const dismissExplain = (paraId, partIdx) => {setSegments((prev) =>prev.map((para) => {if (para.id !== paraId) return para;const newParts = [...para.parts];const part = newParts[partIdx];if (part.type === "explained") {newParts.splice(partIdx, 1, { type: "text", content: part.original });}// Merge adjacent text partsconst merged = [];for (const p of newParts) {if (p.type === "text" && merged.length && merged[merged.length - 1].type === "text") {merged[merged.length - 1] = { type: "text", content: merged[merged.length - 1].content + p.content };} else {merged.push(p);}}return { ...para, parts: merged };}));};return (<div style={{ fontFamily: "'Georgia', serif", background: "#faf8f4", minHeight: "100vh", padding: "0" }}><style>{`@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600&family=Source+Serif+4:ital,opsz,wght@0,8..60,300;0,8..60,400;1,8..60,300&display=swap');* { box-sizing: border-box; }.reader-wrap {max-width: 680px;margin: 0 auto;padding: 60px 32px 120px;}h1.title {font-family: 'Playfair Display', Georgia, serif;font-size: 2.4rem;font-weight: 600;color: #1a1208;margin: 0 0 8px;letter-spacing: -0.5px;line-height: 1.15;}.subtitle {font-family: 'Source Serif 4', Georgia, serif;font-size: 0.9rem;color: #a09070;margin: 0 0 48px;letter-spacing: 0.05em;text-transform: uppercase;}.hint {font-family: 'Source Serif 4', Georgia, serif;font-size: 0.85rem;color: #b0a080;margin: 0 0 36px;display: flex;align-items: center;gap: 8px;}.hint-icon {width: 18px;height: 18px;background: #e8dfc8;border-radius: 50%;display: inline-flex;align-items: center;justify-content: center;font-size: 10px;flex-shrink: 0;}.para {font-family: 'Source Serif 4', Georgia, serif;font-size: 1.08rem;line-height: 1.85;color: #2c2010;margin-bottom: 1.6em;position: relative;}.explained-bubble {display: inline;position: relative;}.explained-original {background: linear-gradient(120deg, #f5e6a3 0%, #f0d870 100%);border-radius: 3px;padding: 1px 3px;text-decoration: line-through;text-decoration-color: #c8a800;color: #6b5a10;font-style: italic;opacity: 0.7;font-size: 0.88em;cursor: pointer;}.explained-text {display: inline-block;background: linear-gradient(135deg, #fffbee 0%, #fff8e0 100%);border-left: 3px solid #d4a800;border-radius: 0 6px 6px 0;padding: 6px 12px 6px 12px;margin: 4px 0;color: #3a2e08;font-size: 0.95rem;line-height: 1.65;box-shadow: 0 2px 8px rgba(180,140,0,0.1);position: relative;}.dismiss-btn {position: absolute;top: 4px;right: 6px;background: none;border: none;color: #c8a800;cursor: pointer;font-size: 14px;padding: 0 2px;opacity: 0.6;line-height: 1;transition: opacity 0.15s;}.dismiss-btn:hover { opacity: 1; }.float-btn {position: absolute;z-index: 100;background: #1a1208;color: #f5e8c0;border: none;border-radius: 6px;padding: 8px 16px;font-family: 'Source Serif 4', Georgia, serif;font-size: 0.82rem;letter-spacing: 0.04em;cursor: pointer;box-shadow: 0 4px 16px rgba(0,0,0,0.25);display: flex;align-items: center;gap: 6px;transition: background 0.15s, transform 0.1s;white-space: nowrap;}.float-btn:hover { background: #2e2010; transform: translateY(-1px); }.float-btn:active { transform: translateY(0); }.loading-overlay {position: fixed;bottom: 28px;left: 50%;transform: translateX(-50%);background: #1a1208;color: #f5e8c0;border-radius: 24px;padding: 10px 22px;font-family: 'Source Serif 4', Georgia, serif;font-size: 0.85rem;display: flex;align-items: center;gap: 10px;box-shadow: 0 4px 20px rgba(0,0,0,0.3);}.spinner {width: 14px;height: 14px;border: 2px solid rgba(245,232,192,0.3);border-top-color: #f5e8c0;border-radius: 50%;animation: spin 0.7s linear infinite;}@keyframes spin { to { transform: rotate(360deg); } }.divider {border: none;border-top: 1px solid #e0d4b8;margin: 40px 0;}`}</style><div className="reader-wrap"><h1 className="title">Text Generation</h1><p className="subtitle">Machine Learning · Reading Guide</p><div className="hint"><span className="hint-icon">✦</span>Highlight any text, then click <em style={{ fontStyle: "italic", color: "#8a7450" }}> Explain </em> to replace it with an AI explanation.</div><hr className="divider" /><div ref={contentRef} style={{ position: "relative" }} onMouseUp={handleMouseUp}>{segments.map((para) => (<p key={para.id} className="para" data-para={para.id}>{para.parts.map((part, pi) =>part.type === "text" ? (<span key={pi} data-para={para.id}>{part.content}</span>) : (<span key={pi} className="explained-bubble">{" "}<span className="explained-text"><button className="dismiss-btn" onClick={() => dismissExplain(para.id, pi)} title="Restore original">✕</button>{part.explanation}</span>{" "}<spanclassName="explained-original"title="Click to restore"onClick={() => dismissExplain(para.id, pi)}>{part.original}</span></span>))}</p>))}{buttonPos && !loading && (<buttonclassName="float-btn"style={{ top: buttonPos.top, left: buttonPos.left }}onMouseDown={(e) => e.preventDefault()}onClick={handleExplain}>✦ Explain</button>)}</div></div>{loading && (<div className="loading-overlay"><div className="spinner" />Generating explanation…</div>)}</div>);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234import gradio as grfrom anthropic import Anthropicclient = Anthropic()CONTENT_PARAGRAPHS = ["Text generation is the task of producing natural language text given an input prompt. It is commonly used for chatbots, creative writing, summarization, and code generation.","Most modern text generation models are based on the transformer architecture and are trained using next-token prediction. The transformer uses self-attention mechanisms to weigh the importance of different words in a sequence when making predictions.","During inference, the model repeatedly samples the most likely next token until a stopping condition is reached. This process is called autoregressive generation. Parameters like temperature and top-p sampling control the randomness and diversity of the output.","Large language models (LLMs) like GPT-4, Claude, and Llama are trained on vast corpora of text from the internet, books, and other sources. This gives them broad world knowledge and language understanding.","Instruction-tuned models are further trained to follow user instructions, using techniques like supervised fine-tuning (SFT) and reinforcement learning from human feedback (RLHF). This makes them much more useful as assistants compared to base language models.",]INITIAL_HTML = "\n".join(f'<p class="content-para" id="para-{i}">{p}</p>'for i, p in enumerate(CONTENT_PARAGRAPHS))def explain_text(selected_text, current_html):if not selected_text or not selected_text.strip():return current_html, "⚠️ Please select some text first."selected_text = selected_text.strip()try:response = client.messages.create(model="claude-opus-4-5",max_tokens=300,messages=[{"role": "user","content": f"You are an ML instructor. Explain this text from a learning resource in 2-3 clear, simple sentences for a beginner:\n\n\"{selected_text}\"",}],)explanation = response.content[0].text.strip()except Exception as e:return current_html, f"❌ Error: {str(e)}"# Replace the selected text in the HTML with explanation blockescaped = selected_text.replace('"', '"')replacement = (f'<mark class="explained-original" title="Original text">{selected_text}</mark>'f'<span class="explanation-block">💡 {explanation}</span>')new_html = current_html.replace(selected_text, replacement, 1)if new_html == current_html:return current_html, "⚠️ Could not find selected text in the document. Try selecting again."return new_html, f"✅ Explained: \"{selected_text[:60]}{'...' if len(selected_text) > 60 else ''}\""def reset_content():return INITIAL_HTML, "", "Document reset."CSS = """@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@600&family=Source+Serif+4:ital,opsz,wght@0,8..60,400;1,8..60,300&display=swap');body { background: #faf8f4 !important; }#reader-content {font-family: 'Source Serif 4', Georgia, serif;font-size: 1.05rem;line-height: 1.85;color: #2c2010;background: #faf8f4;padding: 28px 32px;border-radius: 10px;border: 1px solid #e8dfc8;min-height: 320px;}#reader-content h1 {font-family: 'Playfair Display', Georgia, serif;font-size: 2rem;color: #1a1208;margin-bottom: 4px;}.content-para {margin-bottom: 1.4em;}mark.explained-original {background: linear-gradient(120deg, #f5e6a3, #f0d870);border-radius: 3px;padding: 1px 3px;text-decoration: line-through;text-decoration-color: #c8a800;color: #6b5a10;font-style: italic;opacity: 0.75;}.explanation-block {display: inline-block;background: #fffbee;border-left: 3px solid #d4a800;border-radius: 0 6px 6px 0;padding: 6px 12px;margin: 4px 2px;color: #3a2e08;font-size: 0.93rem;line-height: 1.6;box-shadow: 0 2px 8px rgba(180,140,0,0.1);}#hint-text {font-family: 'Source Serif 4', Georgia, serif;color: #a09070;font-size: 0.88rem;margin-bottom: 8px;}.selected-box textarea {font-family: 'Source Serif 4', Georgia, serif !important;font-size: 0.95rem !important;color: #3a2e08 !important;background: #fffbee !important;border: 1px solid #d4c88a !important;border-radius: 8px !important;}.explain-btn {background: #1a1208 !important;color: #f5e8c0 !important;border-radius: 8px !important;font-family: 'Source Serif 4', Georgia, serif !important;font-size: 0.95rem !important;border: none !important;}.explain-btn:hover {background: #2e2010 !important;}.reset-btn {background: transparent !important;color: #a09070 !important;border: 1px solid #d4c88a !important;border-radius: 8px !important;font-family: 'Source Serif 4', Georgia, serif !important;font-size: 0.9rem !important;}.status-text {font-family: 'Source Serif 4', Georgia, serif !important;color: #6b5a10 !important;font-size: 0.85rem !important;}"""JS_CAPTURE_SELECTION = """function setupSelectionCapture() {document.addEventListener("mouseup", function() {const selection = window.getSelection().toString().trim();if (selection.length > 2) {const textarea = document.querySelector('.selected-box textarea');if (textarea) {const nativeSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;nativeSetter.call(textarea, selection);textarea.dispatchEvent(new Event("input", { bubbles: true }));}}});}setupSelectionCapture();"""with gr.Blocks(css=CSS, js=JS_CAPTURE_SELECTION, title="ML Reader — Highlight & Explain") as demo:gr.HTML("""<div style="max-width: 720px; margin: 0 auto; padding: 32px 16px 0;"><h1 style="font-family:'Playfair Display',Georgia,serif; font-size:2.1rem; color:#1a1208; margin-bottom:4px;">Text Generation</h1><p style="font-family:'Source Serif 4',Georgia,serif; font-size:0.82rem; color:#a09070; letter-spacing:0.08em; text-transform:uppercase; margin:0 0 12px;">Machine Learning · Reading Guide</p><p id="hint-text" style="font-family:'Source Serif 4',Georgia,serif; color:#a09070; font-size:0.88rem; margin-bottom:20px;">✦ Highlight any text below, then click <em>Explain Selection</em> to replace it with an AI explanation.</p></div>""")with gr.Column(elem_style="max-width:720px; margin:0 auto; padding:0 16px 60px;"):content_html = gr.HTML(value=f'<div id="reader-content">{INITIAL_HTML}</div>',label="",)selected_text = gr.Textbox(label="Selected text",placeholder="Highlight text above — it will appear here automatically…",lines=2,elem_classes=["selected-box"],show_label=True,)with gr.Row():explain_btn = gr.Button("✦ Explain Selection", elem_classes=["explain-btn"], variant="primary")reset_btn = gr.Button("↺ Reset", elem_classes=["reset-btn"])status = gr.Textbox(label="", interactive=False, show_label=False, elem_classes=["status-text"])# Hidden state to track current HTMLhtml_state = gr.State(f'<div id="reader-content">{INITIAL_HTML}</div>')explain_btn.click(fn=explain_text,inputs=[selected_text, html_state],outputs=[html_state, status],).then(fn=lambda h: h,inputs=[html_state],outputs=[content_html],)reset_btn.click(fn=reset_content,inputs=[],outputs=[html_state, selected_text, status],).then(fn=lambda h: f'<div id="reader-content">{INITIAL_HTML}</div>',inputs=[html_state],outputs=[content_html],)demo.launch()
app.py+231-373