feat: Add download status polling to UI and Firefox extension
Browse filesFiles changed (4)
47 unmodified lines4849505152535 unmodified lines59606162636494 unmodified lines15916016116216316416516616738 unmodified lines20620720820921021111 unmodified lines2232242252262272285 unmodified lines23423523623723823934 unmodified lines27427527627727827947 unmodified linesconst checkedLayers = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13];try {// Connect to the configured API Spaceconst response = await fetch(`${apiUrl}/analyze/${modelVersion}`, {method: 'POST',5 unmodified lineslayers: checkedLayers})});if (!response.ok) throw new Error('API error');94 unmodified linesconst batchSize = 3;let processedCount = 0;for (let i = 0; i < nodesToProcess.length; i += batchSize) {const batch = nodesToProcess.slice(i, i + batchSize);showToast(`FlowRead analyzing page (${processedCount}/${nodesToProcess.length} blocks)...`, 0);await Promise.all(batch.map(async (node) => {const text = node.nodeValue;38 unmodified linesprocessedCount += batch.length;}showToast(`Done! Analyzed ${processedCount} blocks.`, 2000);}11 unmodified lineslet reFetchCount = 0;let rerenderCount = 0;for (const container of containers) {const oldPreprompt = container.dataset.preprompt || "";5 unmodified linesif (oldPreprompt !== preprompt || oldMode !== saliencyMode || oldModelVersion !== modelVersion) {if (reFetchCount === 0) {showToast("Updating FlowRead elements with new settings...", 0);}try {const response = await fetch(`${apiUrl}/analyze/${modelVersion}`, {34 unmodified lines}}if (reFetchCount > 0) {showToast(`Updated ${reFetchCount} blocks with new AI intent!`, 2000);} else if (rerenderCount > 0) {47 unmodified lines48495051525354555657585960616263646566676869707172735 unmodified lines7980818283848594 unmodified lines18018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021138 unmodified lines25025125225325425525611 unmodified lines2682692702712722732745 unmodified lines28028128228328428528628728828929029129229329429529629729829930034 unmodified lines33533633733833934034134247 unmodified linesconst checkedLayers = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13];try {// Start polling statuslet isFetching = true;const pollStatus = async () => {while (isFetching) {try {const statusRes = await fetch(`${apiUrl}/status`);if (statusRes.ok) {const statusData = await statusRes.json();if (statusData[modelVersion] === "downloading") {showToast(`Downloading Gemma 4 (${modelVersion})... this may take a few minutes.`, 0);}}} catch (e) {// ignore network errors for status polling}await new Promise(r => setTimeout(r, 2000));}};pollStatus();// Connect to the configured API Spaceconst response = await fetch(`${apiUrl}/analyze/${modelVersion}`, {method: 'POST',5 unmodified lineslayers: checkedLayers})});isFetching = false;if (!response.ok) throw new Error('API error');94 unmodified linesconst batchSize = 3;let processedCount = 0;// Polling logic for first requestlet isFetchingStatus = true;const pollStatus = async () => {while (isFetchingStatus) {try {const statusRes = await fetch(`${apiUrl}/status`);if (statusRes.ok) {const statusData = await statusRes.json();if (statusData[modelVersion] === "downloading") {showToast(`Downloading Gemma 4 (${modelVersion})... this may take a few minutes.`, 0);}}} catch (e) {}await new Promise(r => setTimeout(r, 2000));}};pollStatus();for (let i = 0; i < nodesToProcess.length; i += batchSize) {const batch = nodesToProcess.slice(i, i + batchSize);// Only show analyzing text if not downloadingconst statusResTemp = await fetch(`${apiUrl}/status`).catch(() => null);if (!statusResTemp || !statusResTemp.ok || (await statusResTemp.json())[modelVersion] !== "downloading") {showToast(`FlowRead analyzing page (${processedCount}/${nodesToProcess.length} blocks)...`, 0);}await Promise.all(batch.map(async (node) => {const text = node.nodeValue;38 unmodified linesprocessedCount += batch.length;}isFetchingStatus = false;showToast(`Done! Analyzed ${processedCount} blocks.`, 2000);}11 unmodified lineslet reFetchCount = 0;let rerenderCount = 0;let isFetchingStatus = false;for (const container of containers) {const oldPreprompt = container.dataset.preprompt || "";5 unmodified linesif (oldPreprompt !== preprompt || oldMode !== saliencyMode || oldModelVersion !== modelVersion) {if (reFetchCount === 0) {showToast("Updating FlowRead elements with new settings...", 0);isFetchingStatus = true;(async () => {while (isFetchingStatus) {try {const statusRes = await fetch(`${apiUrl}/status`);if (statusRes.ok) {const statusData = await statusRes.json();if (statusData[modelVersion] === "downloading") {showToast(`Downloading Gemma 4 (${modelVersion})... this may take a few minutes.`, 0);}}} catch (e) {}await new Promise(r => setTimeout(r, 2000));}})();}try {const response = await fetch(`${apiUrl}/analyze/${modelVersion}`, {34 unmodified lines}}isFetchingStatus = false;if (reFetchCount > 0) {showToast(`Updated ${reFetchCount} blocks with new AI intent!`, 2000);} else if (rerenderCount > 0) {
235 unmodified lines2362372382392402413 unmodified lines24524624724824925028 unmodified lines2792802812822832842852862872 unmodified lines2902912922932942951 unmodified line297298299300301302303304305306307235 unmodified lines# --- Saliency API (Existing) ---models = {}tokenizers = {}device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")hf_token = os.environ.get("HF_TOKEN")3 unmodified linesreturn models[model_name], tokenizers[model_name]print(f"Loading {model_name} on {device}...")try:if model_name == "27b-4a":# Use Gemma 4 27B in 4-bit (requires CUDA)28 unmodified linesprint(f"Model {model_name} loaded successfully.")models[model_name] = modeltokenizers[model_name] = tokenizerreturn model, tokenizerexcept Exception as e:print(f"Error loading model {model_name}: {e}")raise e# Pre-load default 2b2 unmodified linesexcept:print("Could not preload 2b model.")class TextRequest(BaseModel):text: strlayers: Optional[List[int]] = None # List of layer indices to average1 unmodified linesaliency_mode: str = "local" # "local" or "global"@app.post("/analyze")async def analyze_text_legacy(request: TextRequest):return await analyze_text_model("2b", request)@app.post("/analyze/{model_name}")async def analyze_text_model(model_name: str, request: TextRequest):text = request.textpreprompt = request.preprompt.strip()235 unmodified lines2362372382392402412422432442453 unmodified lines24925025125225325425528 unmodified lines2842852862872882892902912922932942 unmodified lines2972982993003013023033043053061 unmodified line308309310311312313314315316317318235 unmodified lines# --- Saliency API (Existing) ---models = {}tokenizers = {}model_status = {"2b": "unloaded","27b-4a": "unloaded"}device = torch.device("cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu")hf_token = os.environ.get("HF_TOKEN")3 unmodified linesreturn models[model_name], tokenizers[model_name]print(f"Loading {model_name} on {device}...")model_status[model_name] = "downloading"try:if model_name == "27b-4a":# Use Gemma 4 27B in 4-bit (requires CUDA)28 unmodified linesprint(f"Model {model_name} loaded successfully.")models[model_name] = modeltokenizers[model_name] = tokenizermodel_status[model_name] = "loaded"return model, tokenizerexcept Exception as e:print(f"Error loading model {model_name}: {e}")model_status[model_name] = "error"raise e# Pre-load default 2b2 unmodified linesexcept:print("Could not preload 2b model.")@app.get("/status")def get_model_status():return model_statusclass TextRequest(BaseModel):text: strlayers: Optional[List[int]] = None # List of layer indices to average1 unmodified linesaliency_mode: str = "local" # "local" or "global"@app.post("/analyze")def analyze_text_legacy(request: TextRequest):return analyze_text_model("2b", request)@app.post("/analyze/{model_name}")def analyze_text_model(model_name: str, request: TextRequest):text = request.textpreprompt = request.preprompt.strip()
462 unmodified lines4634644654664674685 unmodified lines474475476477478479480481482483484485486487295 unmodified lines783784785786787788789462 unmodified linesconst text = inputArea.value.trim();const preprompt = prepromptInput.value.trim();const saliencyMode = saliencyModeInput.value;const checkedLayers = Array.from(document.querySelectorAll('.layer-cb:checked')).map(cb => parseInt(cb.value));5 unmodified linesanalyzeBtn.disabled = true;loading.style.display = 'block';resultContainer.innerHTML = '';try {const response = await fetch('/analyze', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ text, preprompt, layers: checkedLayers, saliency_mode: saliencyMode })});if (!response.ok) throw new Error('Network response was not ok');295 unmodified lines} catch (err) {console.error(err);alert("Error loading stats.");}}</script>462 unmodified lines4634644654664674684695 unmodified lines475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508295 unmodified lines804805806807808809810811812813814462 unmodified linesconst text = inputArea.value.trim();const preprompt = prepromptInput.value.trim();const saliencyMode = saliencyModeInput.value;const modelVersion = "2b";const checkedLayers = Array.from(document.querySelectorAll('.layer-cb:checked')).map(cb => parseInt(cb.value));5 unmodified linesanalyzeBtn.disabled = true;loading.style.display = 'block';loading.textContent = 'Analyzing text with Gemma 4...';resultContainer.innerHTML = '';let isFetching = true;const pollStatus = async () => {while(isFetching) {try {const statusRes = await fetch('/status');if (statusRes.ok) {const statusData = await statusRes.json();if (statusData[modelVersion] === "downloading") {loading.textContent = `Downloading Gemma 4 (${modelVersion}) Model... this takes a few minutes.`;}}} catch(e) {}await new Promise(r => setTimeout(r, 2000));}};pollStatus();try {const response = await fetch(`/analyze/${modelVersion}`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ text, preprompt, layers: checkedLayers, saliency_mode: saliencyMode })});isFetching = false;if (!response.ok) throw new Error('Network response was not ok');295 unmodified lines} catch (err) {console.error(err);alert("Failed to analyze text.");isFetching = false;} finally {analyzeBtn.disabled = false;loading.style.display = 'none';}}</script>
firefox-extension/content.js+64-1
flowread-extension.zip
main.py+14-3
static/index.html+27-2