Spaces:
Paused
Paused
Upload 27 files
Browse filesFiles changed (4)
- README.md+17-14
- START_HERE.txt+7-6
- app.py+12-12
- floating_tutor.py+386-74
59 unmodified lines606162636465666768697071112 unmodified lines18418518618718818919019119219319419519619714 unmodified lines21221321421521621721859 unmodified linesFace Inference Providers, with automatic verified-local fallback;- a deterministic local tutor for core explanations and image/OCR checking,plus an optional OpenAI route when `OPENAI_API_KEY` is configured;- a persistent bottom-right **Ask Tutor** control on the first page and every tab;it stays in the current viewport while the learner scrolls, opens over the page withoutchanging tabs, keeps its own compact mission-linked conversation, andhyperlinks to the full multimodal tutor;- a protected **Examination lock** that disables the mission generator, everytraining tab, worksheet tools, theory, progress, and Ask Tutor during anactive attempt;- reproducible **Midterm 1** and **Midterm 2** papers with 10 questions each bydefault, plus a default 25-question **Final examination**; all three question112 unmodified lines### Mechanics Tutor ChatThe floating **Ask Tutor** button stays at the bottom-right of the screen onMission Control and every other tab, including while the page is scrolling.Click it to open a separate compact text-tutor box above the button, sothe learner can ask for a first hint, equation choice, or custom clarificationwithout leaving the experiment or worksheet. Its visible question field acceptsfree-form questions and sends them with Enter or **Ask Tutor**. The compact chathas its own conversation and follows the current generated Mission Control orCreative Lab problem and its verified solution. Qwen is the default engine;the verified local and optional OpenAI engines remain selectable. Select **Open fullmultimodal tutor ↗** inside the popup only when voice or image input is needed;that explicit link opens the existing Mechanics Tutor Chat tab in the same14 unmodified lines### Protected examinationsTurn on **Activate examination section** above the mission generator. The apphides and disables all training tabs and the floating Ask Tutor launcher. Afterthe learner starts a paper, the examination switch and paper settings staylocked until the attempt is submitted. Midterm 1 and Midterm 2 default to 10questions and the Final examination defaults to 25; independent sliders can59 unmodified lines6061626364656667686970717273112 unmodified lines18618718818919019119219319419519619719819920014 unmodified lines21521621721821922022159 unmodified linesFace Inference Providers, with automatic verified-local fallback;- a deterministic local tutor for core explanations and image/OCR checking,plus an optional OpenAI route when `OPENAI_API_KEY` is configured;- a draggable **Ask Teacher** control on the first page and every tab; a separategrip moves the real native Gradio button without intercepting its click, theopen panel can be dragged from its header, and both positions remain usableduring scrolling, resizing and browser reloads; it opens over the page withoutchanging tabs, keeps its own compact mission-linked conversation, and linksto the full multimodal tutor;- a protected **Examination lock** that disables the mission generator, everytraining tab, worksheet tools, theory, progress, and Ask Teacher during anactive attempt;- reproducible **Midterm 1** and **Midterm 2** papers with 10 questions each bydefault, plus a default 25-question **Final examination**; all three question112 unmodified lines### Mechanics Tutor ChatThe floating **Ask Teacher** control starts at the bottom-right on MissionControl and every other tab. Drag the **⠿ grip** to move it anywhere in thevisible viewport. The adjoining **Ask Teacher** label is the real native Gradiobutton, so clicking it opens the compact text-tutor directly rather than througha simulated click. The open box can be moved by dragging its header. Learnerscan request a first hint, equation choice, or custom clarification withoutleaving the experiment or worksheet. Its question field sends free-form querieswith Enter or **Ask Teacher**. The compact chat follows the current MissionControl or Creative Lab problem and its verified solution. Qwen is the default engine;the verified local and optional OpenAI engines remain selectable. Select **Open fullmultimodal tutor ↗** inside the popup only when voice or image input is needed;that explicit link opens the existing Mechanics Tutor Chat tab in the same14 unmodified lines### Protected examinationsTurn on **Activate examination section** above the mission generator. The apphides and disables all training tabs and the floating Ask Teacher launcher. Afterthe learner starts a paper, the examination switch and paper settings staylocked until the attempt is submitted. Midterm 1 and Midterm 2 default to 10questions and the Final examination defaults to 25; independent sliders can
36 unmodified lines3738394041424347 unmodified lines91929394959697989910010136 unmodified linesPROTECTED EXAMINATION MODE--------------------------Turn on "Activate examination section" above the mission generator. Trainingtabs and Ask Tutor are hidden. Start Midterm 1, Midterm 2, or the Finalexamination. The two midterms default to 10 questions each and the final to 25;each count is adjustable. Papers use nine formats, including mathematicalcalculation, match the following, diagram interpretation, and paragraph analysis.47 unmodified linesMECHANICS TUTOR CHAT--------------------The "Ask Tutor" button remains at the bottom-right of the visible browser screenwhile scrolling on the first page and every tab. Click it to open a separatecompact chat box above the button without changing the current tab. Type aquestion about the active Mission Control or Creative Lab problem and pressEnter or "Ask Tutor". The reply uses that problem and its verified solution.The default engine is open-source Qwen through Hugging Face. Add HF_TOKEN to theSpace secrets, then select a Qwen model. If the provider is unavailable, theverified local tutor answers automatically.36 unmodified lines3738394041424347 unmodified lines91929394959697989910010110236 unmodified linesPROTECTED EXAMINATION MODE--------------------------Turn on "Activate examination section" above the mission generator. Trainingtabs and Ask Teacher are hidden. Start Midterm 1, Midterm 2, or the Finalexamination. The two midterms default to 10 questions each and the final to 25;each count is adjustable. Papers use nine formats, including mathematicalcalculation, match the following, diagram interpretation, and paragraph analysis.47 unmodified linesMECHANICS TUTOR CHAT--------------------The draggable "Ask Teacher" control starts at the bottom-right of the visiblebrowser screen on the first page and every tab. Drag the separate grip with amouse, pen, or touch; click the actual "Ask Teacher" button to open the compactchat without changing tabs. Drag the open chat from its header. Type a questionabout the active Mission Control or Creative Lab problem and press Enter or"Ask Teacher". The reply uses that problem and its verified solution.The default engine is open-source Qwen through Hugging Face. Add HF_TOKEN to theSpace secrets, then select a Qwen model. If the provider is unavailable, theverified local tutor answers automatically.
533 unmodified lines53453553653753853954059 unmodified lines600601602603604605606478 unmodified lines1085108610871088108910901091734 unmodified lines1826182718281829183018311832189 unmodified lines2022202320242025202620272028202920302031203220332034203514 unmodified lines20502051205220532054205520563 unmodified lines206020612062206320642065206615 unmodified lines2082208320842085208620872088496 unmodified lines258525862587258825892590259125922593533 unmodified lines"""Hide every training surface while the examination section is active."""active = bool(enabled)message = ("🔒 **Examination mode is active.** Training tabs, worksheet tools, theory, progress, and Ask Tutor are unavailable."if activeelse "Training mode is active. Turn on the switch when the student is ready for a protected examination attempt.")59 unmodified linesrender_exam_header(exam),(f"🔒 **{exam['exam_label']} started.** The examination switch and paper settings are locked until submission. ""Ask Tutor and all training sections remain disabled."),gr.update(value=True, interactive=False),gr.update(value=exam["exam_name"], interactive=False),478 unmodified lineswith gr.Row(equal_height=True):with gr.Column(scale=4):gr.Markdown("### 🛡️ Examination lock\nActivate this only when the student is ready. During an active attempt, training tabs and Ask Tutor are unavailable until submission.")with gr.Column(scale=2):exam_mode_toggle = gr.Checkbox(734 unmodified lines"""<section class="exam-lock-banner"><h2>🛡️ Protected examination section</h2><p>Training tools, theory, worksheets, progress, and Ask Tutor are locked while an examination is in progress.</p></section>""")189 unmodified lines# Kept outside gr.Tabs so the launcher and popup remain available on every# tab, including the first page, without changing the learner's current tab.floating_tutor_launcher = gr.Button("💬 Ask Tutor",variant="primary",elem_id="floating-tutor-launcher",)with gr.Group(visible=False, elem_id="floating-tutor-panel") as floating_tutor_panel:with gr.Row(elem_classes=["floating-tutor-dialog-header"]):gr.Markdown("### Floating Mechanics Tutor\n\nMISSION-LINKED QUESTION HELP",elem_classes=["floating-tutor-dialog-title"],scale=8,)14 unmodified lines)floating_tutor_chat = gr.Chatbot(value=tutor_welcome(INITIAL_QUESTION),label="Floating Mechanics Tutor",height=245,latex_delimiters=LATEX_DELIMITERS,elem_classes=["floating-tutor-chat"],3 unmodified linesfloating_equation_btn = gr.Button("Equation choice", size="sm")with gr.Group(elem_classes=["floating-tutor-composer"]):gr.Markdown("**Ask about the active problem** · Type below and press Enter or Ask Tutor.",elem_classes=["floating-tutor-composer-note"],)floating_tutor_text = gr.Textbox(15 unmodified lines)with gr.Row():floating_tutor_send_btn = gr.Button("Enter · Ask Tutor",variant="primary",elem_classes=["submit-btn"],)496 unmodified linesinputs=[custom_question_state],outputs=[custom_md_file, custom_docx_file, custom_pdf_file],)# Install a document-body launcher after Gradio has mounted. It stays in# the visible browser viewport during page or nested-container scrolling# and forwards clicks to the native Gradio event above.demo.load(fn=None, js=FLOATING_TUTOR_VIEWPORT_JS, show_progress="hidden")533 unmodified lines53453553653753853954059 unmodified lines600601602603604605606478 unmodified lines1085108610871088108910901091734 unmodified lines1826182718281829183018311832189 unmodified lines2022202320242025202620272028202920302031203220332034203514 unmodified lines20502051205220532054205520563 unmodified lines206020612062206320642065206615 unmodified lines2082208320842085208620872088496 unmodified lines258525862587258825892590259125922593533 unmodified lines"""Hide every training surface while the examination section is active."""active = bool(enabled)message = ("🔒 **Examination mode is active.** Training tabs, worksheet tools, theory, progress, and Ask Teacher are unavailable."if activeelse "Training mode is active. Turn on the switch when the student is ready for a protected examination attempt.")59 unmodified linesrender_exam_header(exam),(f"🔒 **{exam['exam_label']} started.** The examination switch and paper settings are locked until submission. ""Ask Teacher and all training sections remain disabled."),gr.update(value=True, interactive=False),gr.update(value=exam["exam_name"], interactive=False),478 unmodified lineswith gr.Row(equal_height=True):with gr.Column(scale=4):gr.Markdown("### 🛡️ Examination lock\nActivate this only when the student is ready. During an active attempt, training tabs and Ask Teacher are unavailable until submission.")with gr.Column(scale=2):exam_mode_toggle = gr.Checkbox(734 unmodified lines"""<section class="exam-lock-banner"><h2>🛡️ Protected examination section</h2><p>Training tools, theory, worksheets, progress, and Ask Teacher are locked while an examination is in progress.</p></section>""")189 unmodified lines# Kept outside gr.Tabs so the launcher and popup remain available on every# tab, including the first page, without changing the learner's current tab.floating_tutor_launcher = gr.Button("💬 Ask Teacher",variant="primary",elem_id="floating-tutor-launcher",)with gr.Group(visible=False, elem_id="floating-tutor-panel") as floating_tutor_panel:with gr.Row(elem_classes=["floating-tutor-dialog-header"]):gr.Markdown("### Ask Teacher · Mechanics\n\nDRAG THIS HEADER TO MOVE · MISSION-LINKED HELP",elem_classes=["floating-tutor-dialog-title"],scale=8,)14 unmodified lines)floating_tutor_chat = gr.Chatbot(value=tutor_welcome(INITIAL_QUESTION),label="Ask Teacher · Mechanics",height=245,latex_delimiters=LATEX_DELIMITERS,elem_classes=["floating-tutor-chat"],3 unmodified linesfloating_equation_btn = gr.Button("Equation choice", size="sm")with gr.Group(elem_classes=["floating-tutor-composer"]):gr.Markdown("**Ask about the active problem** · Type below and press Enter or Ask Teacher.",elem_classes=["floating-tutor-composer-note"],)floating_tutor_text = gr.Textbox(15 unmodified lines)with gr.Row():floating_tutor_send_btn = gr.Button("Enter · Ask Teacher",variant="primary",elem_classes=["submit-btn"],)496 unmodified linesinputs=[custom_question_state],outputs=[custom_md_file, custom_docx_file, custom_pdf_file],)# Install a document-body drag grip after Gradio has mounted. The real# clickable launcher stays in Gradio's component tree and is positioned# beside the grip, preserving the native open event above.demo.load(fn=None, js=FLOATING_TUTOR_VIEWPORT_JS, show_progress="hidden")
5 unmodified lines678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061623 unmodified lines666768697071727374757677787925 unmodified lines10510610710810911015 unmodified lines12612712812913013125 unmodified lines15715815916016116216316416513 unmodified lines1791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412421 unmodified line2442452462472482492502512522532542552562572582592602612622632642655 unmodified linesFLOATING_TUTOR_CSS = r"""#floating-tutor-viewport-launcher {align-items: center !important;background: linear-gradient(110deg, #6d28d9, #db2777) !important;border: 1px solid rgba(255, 255, 255, .48) !important;border-radius: 999px !important;bottom: max(18px, env(safe-area-inset-bottom)) !important;box-shadow: 0 14px 34px rgba(76, 29, 149, .36) !important;color: white !important;cursor: pointer !important;display: inline-flex !important;font-family: inherit !important;font-size: 14px !important;font-weight: 850 !important;gap: 7px !important;justify-content: center !important;left: auto !important;line-height: 1.2 !important;margin: 0 !important;min-height: 44px !important;min-width: 142px !important;opacity: 1 !important;padding: 10px 18px !important;pointer-events: auto !important;position: fixed !important;right: max(18px, env(safe-area-inset-right)) !important;top: auto !important;transform: translateZ(0);visibility: visible !important;width: auto !important;z-index: 2147483000 !important;}#floating-tutor-viewport-launcher:hover {box-shadow: 0 17px 40px rgba(76, 29, 149, .44) !important;transform: translateY(-2px) translateZ(0);}#floating-tutor-viewport-launcher:focus-visible {outline: 3px solid rgba(34, 211, 238, .78) !important;outline-offset: 3px !important;}/* The original component remains the native Gradio event source. JavaScriptonly moves it off-screen after the viewport proxy has been installed. */#floating-tutor-launcher.viewport-proxy-active {height: 1px !important;left: -10000px !important;min-height: 1px !important;min-width: 1px !important;opacity: 0 !important;overflow: hidden !important;pointer-events: none !important;position: absolute !important;top: 0 !important;width: 1px !important;}#floating-tutor-launcher {bottom: 22px !important;left: auto !important;3 unmodified linesright: 22px !important;top: auto !important;width: auto !important;z-index: 1001 !important;}#floating-tutor-launcher,#floating-tutor-launcher button,button#floating-tutor-launcher {background: linear-gradient(110deg, #6d28d9, #db2777) !important;border: 1px solid rgba(255, 255, 255, .48) !important;border-radius: 999px !important;box-shadow: 0 14px 34px rgba(76, 29, 149, .36) !important;color: white !important;font-weight: 850 !important;25 unmodified linesborder-bottom: 1px solid #e2e8f0;margin-bottom: 7px;padding-bottom: 7px;}.floating-tutor-dialog-title h3 {color: #172554;15 unmodified linesmin-width: 36px !important;padding: 0 !important;width: 36px !important;}#floating-open-full-tutor {color: #6d28d9 !important;25 unmodified linesbottom: max(12px, env(safe-area-inset-bottom)) !important;min-height: 42px !important;min-width: 132px !important;padding: 9px 15px !important;right: max(12px, env(safe-area-inset-right)) !important;}#floating-tutor-launcher {bottom: 13px !important;right: 13px !important;13 unmodified lines# Gradio components can live below transformed or scrolling ancestors, both of# which alter how CSS ``position: fixed`` behaves. This small browser-side# adapter attaches the visible launcher directly to ``document.body`` and# delegates each click to the native Gradio button. The dialog therefore keeps# its normal Python event wiring while the launcher remains viewport-pinned.FLOATING_TUTOR_VIEWPORT_JS = r"""() => {const PROXY_ID = "floating-tutor-viewport-launcher";const NATIVE_ID = "floating-tutor-launcher";const nativeButton = () => {const host = document.getElementById(NATIVE_ID);if (!host) return null;if (host.matches("button")) return host;return host.querySelector("button");};const pinToViewport = (button) => {if (!button) return;const mobile = window.matchMedia("(max-width: 520px)").matches;const inset = mobile ? 12 : 18;const viewport = window.visualViewport;const extraRight = viewport? Math.max(0, window.innerWidth - viewport.offsetLeft - viewport.width): 0;const extraBottom = viewport? Math.max(0, window.innerHeight - viewport.offsetTop - viewport.height): 0;button.style.setProperty("position", "fixed", "important");button.style.setProperty("right", `${inset + extraRight}px`, "important");button.style.setProperty("bottom", `${inset + extraBottom}px`, "important");button.style.setProperty("left", "auto", "important");button.style.setProperty("top", "auto", "important");button.style.setProperty("z-index", "2147483000", "important");};const install = () => {let proxy = document.getElementById(PROXY_ID);if (!proxy) {proxy = document.createElement("button");proxy.id = PROXY_ID;proxy.type = "button";proxy.textContent = "💬 Ask Tutor";proxy.setAttribute("aria-label", "Open Ask Tutor for the active mechanics problem");proxy.setAttribute("aria-controls", "floating-tutor-panel");proxy.addEventListener("click", () => {const target = nativeButton();if (target) target.click();});document.body.appendChild(proxy);}pinToViewport(proxy);const nativeHost = document.getElementById(NATIVE_ID);if (nativeHost) {nativeHost.classList.add("viewport-proxy-active");nativeHost.setAttribute("aria-hidden", "true");const target = nativeButton();if (target) target.tabIndex = -1;}return proxy;};1 unmodified lineif (!window.__m1TutorViewportLauncherInstalled) {window.__m1TutorViewportLauncherInstalled = true;let frame = 0;const schedulePin = () => {window.cancelAnimationFrame(frame);frame = window.requestAnimationFrame(() => pinToViewport(install()));};window.addEventListener("scroll", schedulePin, {passive: true, capture: true});document.addEventListener("scroll", schedulePin, {passive: true, capture: true});window.addEventListener("resize", schedulePin, {passive: true});window.addEventListener("orientationchange", schedulePin, {passive: true});if (window.visualViewport) {window.visualViewport.addEventListener("scroll", schedulePin, {passive: true});window.visualViewport.addEventListener("resize", schedulePin, {passive: true});}new MutationObserver(() => install()).observe(document.body, {childList: true,subtree: true,});}install();5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071723 unmodified lines767778798081828384858687888990919225 unmodified lines11811912012112212312412512612712812915 unmodified lines14514614714814915015125 unmodified lines17717817918018118218318418518618718813 unmodified lines2022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425431 unmodified line5455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775 unmodified linesFLOATING_TUTOR_CSS = r"""#floating-tutor-viewport-launcher {align-items: center !important;background: transparent !important;border: 0 !important;border-radius: 0 !important;bottom: max(18px, env(safe-area-inset-bottom)) !important;box-shadow: none !important;color: white !important;cursor: default !important;display: inline-flex !important;font-family: inherit !important;font-size: 14px !important;font-weight: 850 !important;gap: 0 !important;justify-content: center !important;left: auto !important;line-height: 1.2 !important;margin: 0 !important;min-height: 44px !important;min-width: 176px !important;opacity: 1 !important;padding: 0 !important;pointer-events: none !important;position: fixed !important;right: max(18px, env(safe-area-inset-right)) !important;top: auto !important;transform: translateZ(0);user-select: none !important;visibility: visible !important;width: auto !important;z-index: 2147483000 !important;}#floating-tutor-viewport-launcher.is-dragging {transition: none !important;}#floating-tutor-viewport-launcher .ask-teacher-drag-handle {align-items: center;align-self: stretch;background: linear-gradient(110deg, #6d28d9, #8b2bd5);border: 1px solid rgba(255, 255, 255, .48);border-radius: 999px 0 0 999px;color: rgba(255, 255, 255, .82);cursor: grab;display: inline-flex;font-size: 17px;font-weight: 900;justify-content: center;min-width: 38px;padding: 0 10px;pointer-events: auto;box-shadow: 0 14px 34px rgba(76, 29, 149, .36);touch-action: none;}#floating-tutor-viewport-launcher.is-dragging .ask-teacher-drag-handle {cursor: grabbing;}#floating-tutor-viewport-launcher .ask-teacher-drag-handle:focus-visible {outline: 3px solid rgba(34, 211, 238, .78) !important;outline-offset: -3px !important;}/* This is the real Gradio button. It remains in Gradio's component tree andis positioned beside the body-level drag grip, so clicks never need to besimulated or forwarded. */#floating-tutor-launcher {bottom: 22px !important;left: auto !important;3 unmodified linesright: 22px !important;top: auto !important;width: auto !important;opacity: 1 !important;pointer-events: auto !important;visibility: visible !important;z-index: 2147483000 !important;}#floating-tutor-launcher,#floating-tutor-launcher button,button#floating-tutor-launcher {background: linear-gradient(110deg, #6d28d9, #db2777) !important;border: 1px solid rgba(255, 255, 255, .48) !important;border-radius: 0 999px 999px 0 !important;box-shadow: 0 14px 34px rgba(76, 29, 149, .36) !important;color: white !important;font-weight: 850 !important;25 unmodified linesborder-bottom: 1px solid #e2e8f0;margin-bottom: 7px;padding-bottom: 7px;cursor: grab;touch-action: none;user-select: none;}#floating-tutor-panel.panel-is-dragging .floating-tutor-dialog-header {cursor: grabbing;}.floating-tutor-dialog-title h3 {color: #172554;15 unmodified linesmin-width: 36px !important;padding: 0 !important;width: 36px !important;cursor: pointer !important;}#floating-open-full-tutor {color: #6d28d9 !important;25 unmodified linesbottom: max(12px, env(safe-area-inset-bottom)) !important;min-height: 42px !important;min-width: 132px !important;right: max(12px, env(safe-area-inset-right)) !important;}#floating-tutor-viewport-launcher .ask-teacher-drag-handle {min-width: 34px;padding: 0 8px;}#floating-tutor-launcher {bottom: 13px !important;right: 13px !important;13 unmodified lines# Gradio components can live below transformed or scrolling ancestors, both of# which alter how CSS ``position: fixed`` behaves. This browser-side adapter# attaches only a drag grip to ``document.body`` and keeps the real visible# Gradio button in its original component tree. Clicking therefore invokes the# native Gradio event directly while the paired launcher remains viewport-pinned.FLOATING_TUTOR_VIEWPORT_JS = r"""() => {const PROXY_ID = "floating-tutor-viewport-launcher";const NATIVE_ID = "floating-tutor-launcher";const PANEL_ID = "floating-tutor-panel";const LAUNCHER_POSITION_KEY = "m1-ask-teacher-launcher-position-v1";const PANEL_POSITION_KEY = "m1-ask-teacher-panel-position-v1";const DRAG_THRESHOLD = 5;let launcherPosition = null;let panelPosition = null;const readPosition = (key) => {try {const value = JSON.parse(window.localStorage.getItem(key) || "null");if (value && Number.isFinite(value.x) && Number.isFinite(value.y)) {return {x: Math.max(0, Math.min(1, value.x)), y: Math.max(0, Math.min(1, value.y))};}} catch (_) {}return null;};const writePosition = (key, value) => {try { window.localStorage.setItem(key, JSON.stringify(value)); } catch (_) {}};launcherPosition = readPosition(LAUNCHER_POSITION_KEY);panelPosition = readPosition(PANEL_POSITION_KEY);const nativeHost = () => document.getElementById(NATIVE_ID);const nativeButton = () => {const host = nativeHost();if (!host) return null;if (host.matches("button")) return host;return host.querySelector("button");};const viewportBounds = () => {const mobile = window.matchMedia("(max-width: 520px)").matches;const inset = mobile ? 12 : 18;const viewport = window.visualViewport;const left = viewport ? viewport.offsetLeft : 0;const top = viewport ? viewport.offsetTop : 0;const width = viewport ? viewport.width : document.documentElement.clientWidth;const height = viewport ? viewport.height : document.documentElement.clientHeight;return {left, top, width, height, right: left + width, bottom: top + height, inset};};const clamp = (value, minimum, maximum) => Math.min(Math.max(value, minimum), Math.max(minimum, maximum));const normalizedPosition = (rect) => {const bounds = viewportBounds();const safeLeft = bounds.left + bounds.inset;const safeTop = bounds.top + bounds.inset;const horizontalRange = Math.max(1, bounds.width - bounds.inset * 2 - rect.width);const verticalRange = Math.max(1, bounds.height - bounds.inset * 2 - rect.height);return {x: clamp((rect.left - safeLeft) / horizontalRange, 0, 1),y: clamp((rect.top - safeTop) / verticalRange, 0, 1),};};const positionFromNormalized = (element, position, fallback) => {if (!element) return;const bounds = viewportBounds();const rect = element.getBoundingClientRect();const safeLeft = bounds.left + bounds.inset;const safeTop = bounds.top + bounds.inset;const horizontalRange = Math.max(0, bounds.width - bounds.inset * 2 - rect.width);const verticalRange = Math.max(0, bounds.height - bounds.inset * 2 - rect.height);const selected = position || fallback;element.style.setProperty("position", "fixed", "important");element.style.setProperty("left", `${safeLeft + selected.x * horizontalRange}px`, "important");element.style.setProperty("top", `${safeTop + selected.y * verticalRange}px`, "important");element.style.setProperty("right", "auto", "important");element.style.setProperty("bottom", "auto", "important");element.style.setProperty("transform", "translate3d(0, 0, 0)", "important");};const alignNativeLauncher = (proxy) => {const host = nativeHost();const handle = proxy?.querySelector(".ask-teacher-drag-handle");if (!proxy || !host || !handle) return null;host.classList.remove("viewport-proxy-active");host.removeAttribute("aria-hidden");const target = nativeButton();if (target) target.removeAttribute("tabindex");const proxyRect = proxy.getBoundingClientRect();const handleRect = handle.getBoundingClientRect();const desiredLeft = proxyRect.left + handleRect.width - 2;const desiredTop = proxyRect.top;host.style.setProperty("position", "fixed", "important");host.style.setProperty("left", `${desiredLeft}px`, "important");host.style.setProperty("top", `${desiredTop}px`, "important");host.style.setProperty("right", "auto", "important");host.style.setProperty("bottom", "auto", "important");host.style.setProperty("transform", "none", "important");host.style.setProperty("opacity", "1", "important");host.style.setProperty("visibility", "visible", "important");host.style.setProperty("pointer-events", "auto", "important");host.style.setProperty("z-index", "2147483000", "important");// A transformed Gradio ancestor can shift fixed coordinates. Correct the// native host in place without moving it out of Gradio's event tree.const actual = host.getBoundingClientRect();if (Math.abs(actual.left - desiredLeft) > 0.5) {host.style.setProperty("left", `${desiredLeft + desiredLeft - actual.left}px`, "important");}if (Math.abs(actual.top - desiredTop) > 0.5) {host.style.setProperty("top", `${desiredTop + desiredTop - actual.top}px`, "important");}return host;};const positionLauncher = (proxy) => {if (!proxy || proxy.classList.contains("is-dragging")) return;const host = nativeHost();const hostWidth = Math.max(132, host?.getBoundingClientRect().width || 142);const handle = proxy.querySelector(".ask-teacher-drag-handle");const handleWidth = Math.max(34, handle?.getBoundingClientRect().width || 38);proxy.style.setProperty("width", `${hostWidth + handleWidth - 2}px`, "important");positionFromNormalized(proxy, launcherPosition, {x: 1, y: 1});proxy.style.setProperty("visibility", "visible", "important");proxy.style.setProperty("position", "fixed", "important");proxy.style.setProperty("z-index", "2147483001", "important");alignNativeLauncher(proxy);};const positionPanel = (button, panel) => {if (!panel || panel.classList.contains("panel-is-dragging")) return;const bounds = viewportBounds();const panelWidth = Math.max(180, Math.min(430, bounds.width - bounds.inset * 2));const maximumHeight = Math.max(140, bounds.height - bounds.inset * 2);panel.style.setProperty("width", `${panelWidth}px`, "important");panel.style.setProperty("max-height", `${maximumHeight}px`, "important");panel.style.setProperty("position", "fixed", "important");panel.style.setProperty("right", "auto", "important");panel.style.setProperty("bottom", "auto", "important");panel.style.setProperty("transform", "translate3d(0, 0, 0)", "important");panel.style.setProperty("z-index", "2147482999", "important");if (panelPosition) {positionFromNormalized(panel, panelPosition, {x: 1, y: 0});return;}const launcherRect = button?.getBoundingClientRect();const panelRect = panel.getBoundingClientRect();if (!launcherRect) {positionFromNormalized(panel, null, {x: 1, y: 0});return;}const gap = 12;const safeLeft = bounds.left + bounds.inset;const safeTop = bounds.top + bounds.inset;const safeRight = bounds.right - bounds.inset;const safeBottom = bounds.bottom - bounds.inset;const spaceAbove = Math.max(0, launcherRect.top - safeTop - gap);const spaceBelow = Math.max(0, safeBottom - launcherRect.bottom - gap);const useAbove = spaceAbove >= spaceBelow;const availableHeight = Math.max(140, useAbove ? spaceAbove : spaceBelow);panel.style.setProperty("max-height", `${Math.min(maximumHeight, availableHeight)}px`, "important");const estimatedHeight = Math.min(Math.max(220, panelRect.height || 520),Math.min(maximumHeight, availableHeight),);const left = clamp(launcherRect.right - panelWidth, safeLeft, safeRight - panelWidth);const top = useAbove? clamp(launcherRect.top - gap - estimatedHeight, safeTop, safeBottom - estimatedHeight): clamp(launcherRect.bottom + gap, safeTop, safeBottom - estimatedHeight);panel.style.setProperty("left", `${left}px`, "important");panel.style.setProperty("top", `${top}px`, "important");};const configurePanel = (proxy) => {const panel = document.getElementById(PANEL_ID);if (!panel) return null;// Keep the panel inside Gradio's component tree. Moving this node to// document.body detaches Gradio/Svelte listeners and breaks open, close,// send, clear, Enter-submit, and Qwen response updates.positionPanel(nativeHost() || proxy, panel);makePanelDraggable(panel);return panel;};const makeLauncherDraggable = (launcher) => {if (!launcher || launcher.dataset.askTeacherDraggable === "true") return;const handle = launcher.querySelector(".ask-teacher-drag-handle");if (!handle) return;launcher.dataset.askTeacherDraggable = "true";let drag = null;handle.addEventListener("pointerdown", (event) => {if (event.button !== undefined && event.button !== 0) return;const rect = launcher.getBoundingClientRect();drag = {pointerId: event.pointerId,startX: event.clientX,startY: event.clientY,originLeft: rect.left,originTop: rect.top,width: rect.width,height: rect.height,moved: false,};try { handle.setPointerCapture(event.pointerId); } catch (_) {}event.preventDefault();event.stopPropagation();});handle.addEventListener("pointermove", (event) => {if (!drag || event.pointerId !== drag.pointerId) return;const dx = event.clientX - drag.startX;const dy = event.clientY - drag.startY;if (!drag.moved && Math.hypot(dx, dy) < DRAG_THRESHOLD) return;drag.moved = true;event.preventDefault();event.stopPropagation();launcher.classList.add("is-dragging");const bounds = viewportBounds();const left = clamp(drag.originLeft + dx,bounds.left + bounds.inset,bounds.right - bounds.inset - drag.width,);const top = clamp(drag.originTop + dy,bounds.top + bounds.inset,bounds.bottom - bounds.inset - drag.height,);launcher.style.setProperty("left", `${left}px`, "important");launcher.style.setProperty("top", `${top}px`, "important");launcher.style.setProperty("right", "auto", "important");launcher.style.setProperty("bottom", "auto", "important");const host = alignNativeLauncher(launcher);if (!panelPosition) positionPanel(host || launcher, document.getElementById(PANEL_ID));});const finishDrag = (event) => {if (!drag || (event.pointerId !== undefined && event.pointerId !== drag.pointerId)) return;if (drag.moved) {launcherPosition = normalizedPosition(launcher.getBoundingClientRect());writePosition(LAUNCHER_POSITION_KEY, launcherPosition);}launcher.classList.remove("is-dragging");try { handle.releasePointerCapture(drag.pointerId); } catch (_) {}drag = null;};handle.addEventListener("pointerup", finishDrag);handle.addEventListener("pointercancel", finishDrag);};function makePanelDraggable(panel) {const header = panel?.querySelector(".floating-tutor-dialog-header");if (!header || header.dataset.askTeacherDraggable === "true") return;header.dataset.askTeacherDraggable = "true";header.setAttribute("title", "Drag to move Ask Teacher");let drag = null;header.addEventListener("pointerdown", (event) => {if (event.button !== undefined && event.button !== 0) return;if (event.target.closest("button, a, input, textarea, select")) return;const rect = panel.getBoundingClientRect();drag = {pointerId: event.pointerId,startX: event.clientX,startY: event.clientY,originLeft: rect.left,originTop: rect.top,width: rect.width,height: rect.height,};panel.classList.add("panel-is-dragging");try { header.setPointerCapture(event.pointerId); } catch (_) {}event.preventDefault();});header.addEventListener("pointermove", (event) => {if (!drag || event.pointerId !== drag.pointerId) return;event.preventDefault();const bounds = viewportBounds();const left = clamp(drag.originLeft + event.clientX - drag.startX,bounds.left + bounds.inset,bounds.right - bounds.inset - drag.width,);const top = clamp(drag.originTop + event.clientY - drag.startY,bounds.top + bounds.inset,bounds.bottom - bounds.inset - drag.height,);panel.style.setProperty("left", `${left}px`, "important");panel.style.setProperty("top", `${top}px`, "important");panel.style.setProperty("right", "auto", "important");panel.style.setProperty("bottom", "auto", "important");});const finishPanelDrag = (event) => {if (!drag || (event.pointerId !== undefined && event.pointerId !== drag.pointerId)) return;panelPosition = normalizedPosition(panel.getBoundingClientRect());writePosition(PANEL_POSITION_KEY, panelPosition);panel.classList.remove("panel-is-dragging");try { header.releasePointerCapture(drag.pointerId); } catch (_) {}drag = null;};header.addEventListener("pointerup", finishPanelDrag);header.addEventListener("pointercancel", finishPanelDrag);}const install = () => {let proxy = document.getElementById(PROXY_ID);if (!proxy) {proxy = document.createElement("div");proxy.id = PROXY_ID;proxy.innerHTML = '<button type="button" class="ask-teacher-drag-handle" aria-label="Drag Ask Teacher to another position" title="Drag to move Ask Teacher">⠿</button>';document.body.appendChild(proxy);}positionLauncher(proxy);makeLauncherDraggable(proxy);configurePanel(proxy);const target = nativeButton();if (target && target.dataset.askTeacherPanelPositionHook !== "true") {target.dataset.askTeacherPanelPositionHook = "true";target.addEventListener("click", () => {// Do not prevent, replace, or forward this click. Gradio receives it// normally; these delayed calls only position the panel after render.window.requestAnimationFrame(() => configurePanel(proxy));window.setTimeout(() => configurePanel(proxy), 120);window.setTimeout(() => configurePanel(proxy), 360);});}return proxy;};1 unmodified lineif (!window.__m1TutorViewportLauncherInstalled) {window.__m1TutorViewportLauncherInstalled = true;let frame = 0;const schedulePosition = () => {window.cancelAnimationFrame(frame);frame = window.requestAnimationFrame(() => {const proxy = install();positionLauncher(proxy);configurePanel(proxy);});};window.__m1AskTeacherSchedulePosition = schedulePosition;window.addEventListener("scroll", schedulePosition, {passive: true, capture: true});document.addEventListener("scroll", schedulePosition, {passive: true, capture: true});window.addEventListener("resize", schedulePosition, {passive: true});window.addEventListener("orientationchange", schedulePosition, {passive: true});if (window.visualViewport) {window.visualViewport.addEventListener("scroll", schedulePosition, {passive: true});window.visualViewport.addEventListener("resize", schedulePosition, {passive: true});}new MutationObserver(() => install()).observe(document.body, {childList: true,subtree: true,});if (window.ResizeObserver) {const resizeObserver = new ResizeObserver(schedulePosition);resizeObserver.observe(document.documentElement);resizeObserver.observe(document.body);window.__m1AskTeacherResizeObserver = resizeObserver;}}install();
README.md+17-14
START_HERE.txt+7-6
app.py+12-12
floating_tutor.py+386-74