Spaces:
Running
Running
Update index.html
Browse filesadd extra layer for correct caption
26 unmodified lines272829303132331 unmodified line353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879806 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514626 unmodified lines<p id="status"></p><h2>Caption</h2><p id="caption"></p><script type="module">1 unmodified lineFlorence2ForConditionalGeneration,AutoProcessor,AutoTokenizer,RawImage} from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";const imageInput = document.getElementById("imageInput");const preview = document.getElementById("preview");const captionButton = document.getElementById("captionButton");const status = document.getElementById("status");const caption = document.getElementById("caption");const MODEL_ID = "onnx-community/Florence-2-base-ft";let selectedFile = null;let model = null;let processor = null;let tokenizer = null;imageInput.addEventListener("change", (event) => {selectedFile = event.target.files[0];if (!selectedFile) {captionButton.disabled = true;preview.style.display = "none";return;}preview.src = URL.createObjectURL(selectedFile);preview.style.display = "block";captionButton.disabled = false;caption.textContent = "";status.textContent = "";});async function loadModel() {if (model) {return;}status.textContent = "Loading Florence-2 model...";model = await Florence2ForConditionalGeneration.from_pretrained(MODEL_ID,{6 unmodified linesdevice: "webgpu",});processor = await AutoProcessor.from_pretrained(MODEL_ID);tokenizer = await AutoTokenizer.from_pretrained(MODEL_ID);}captionButton.addEventListener("click", async () => {try {captionButton.disabled = true;caption.textContent = "";await loadModel();status.textContent = "Preparing image...";const image = await RawImage.fromBlob(selectedFile);const task = "<CAPTION>";const visionInputs = await processor(image);const prompts = processor.construct_prompts(task);const textInputs = tokenizer(prompts);status.textContent = "Generating caption...";const generatedIds = await model.generate({...textInputs,...visionInputs,max_new_tokens: 100,});const generatedText = tokenizer.batch_decode(generatedIds,{skip_special_tokens: false,})[0];const result = processor.post_process_generation(generatedText,task,image.size);caption.textContent =result[task] || "No caption generated.";status.textContent = "Done.";} catch (error) {console.error(error);status.textContent ="Error: " + (error.message || error);} finally {captionButton.disabled = false;}26 unmodified lines272829303132333435361 unmodified line383940414243444546474849505152535455565758596061626364656667686970717273747576777879806 unmodified lines8788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020126 unmodified lines<p id="status"></p><h2>Raw caption</h2><p id="rawCaption"></p><h2>Refined caption</h2><p id="caption"></p><script type="module">1 unmodified lineFlorence2ForConditionalGeneration,AutoProcessor,AutoTokenizer,RawImage,pipeline} from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";const imageInput = document.getElementById("imageInput");const preview = document.getElementById("preview");const captionButton = document.getElementById("captionButton");const status = document.getElementById("status");const rawCaptionEl = document.getElementById("rawCaption");const caption = document.getElementById("caption");const MODEL_ID = "onnx-community/Florence-2-base-ft";const REFINER_ID = "onnx-community/Qwen2.5-0.5B-Instruct";let selectedFile = null;let model = null;let processor = null;let tokenizer = null;let refiner = null;// ---------- filename helpers ----------function cleanFilename(name) {let base = name.replace(/\.[^.]+$/, ""); // drop extensionbase = base.replace(/[_-]+/g, " "); // _ and - -> spacebase = base.replace(/\b(img|dsc|photo|image|picture|pic|file|screenshot|final|copy|edit|v\d+)\b/gi," "); // drop generic tokensbase = base.replace(/\b\d+\b/g, " "); // drop bare numbersbase = base.replace(/\s+/g, " ").trim();return base;}// ---------- model loading ----------async function loadCaptionModel() {if (model) return;status.textContent = "Loading Florence-2 model...";model = await Florence2ForConditionalGeneration.from_pretrained(MODEL_ID,{6 unmodified linesdevice: "webgpu",});processor = await AutoProcessor.from_pretrained(MODEL_ID);tokenizer = await AutoTokenizer.from_pretrained(MODEL_ID);}async function loadRefiner() {if (refiner) return;status.textContent = "Loading caption refiner...";refiner = await pipeline("text-generation", REFINER_ID, {dtype: "q4",device: "webgpu",});}// ---------- refinement ----------async function refine(rawCaption, filename) {const hints = cleanFilename(filename);const system ="You rewrite image captions into ONE natural, fluent sentence. " +"Use the filename hints only if they add useful information for describing " +"the image; ignore them if they are generic or irrelevant. " +"Do not invent details that are not in the caption or hints. " +"Output only the rewritten sentence, nothing else.";const user = hints? `Raw caption: ${rawCaption}\nFilename hints: ${hints}\nRewritten caption:`: `Raw caption: ${rawCaption}\n(No useful filename hints.)\nRewritten caption:`;const out = await refiner([{ role: "system", content: system },{ role: "user", content: user },],{ max_new_tokens: 60, do_sample: false });const generated = out[0].generated_text;// transformers.js returns either a string or the full messages arraylet text;if (Array.isArray(generated)) {text = generated[generated.length - 1].content;} else {text = generated;}return (text || "").trim();}// ---------- file input ----------imageInput.addEventListener("change", (event) => {selectedFile = event.target.files[0];if (!selectedFile) {captionButton.disabled = true;preview.style.display = "none";return;}preview.src = URL.createObjectURL(selectedFile);preview.style.display = "block";captionButton.disabled = false;caption.textContent = "";rawCaptionEl.textContent = "";status.textContent = "";});// ---------- main ----------captionButton.addEventListener("click", async () => {try {captionButton.disabled = true;caption.textContent = "";rawCaptionEl.textContent = "";await loadCaptionModel();status.textContent = "Preparing image...";const image = await RawImage.fromBlob(selectedFile);const task = "<CAPTION>";const visionInputs = await processor(image);const prompts = processor.construct_prompts(task);const textInputs = tokenizer(prompts);status.textContent = "Generating caption...";const generatedIds = await model.generate({...textInputs,...visionInputs,max_new_tokens: 100,});const generatedText = tokenizer.batch_decode(generatedIds,{ skip_special_tokens: false })[0];const result = processor.post_process_generation(generatedText,task,image.size);const rawCaption = result[task] || "";rawCaptionEl.textContent = rawCaption || "(no caption)";await loadRefiner();status.textContent = "Refining caption...";const refined = await refine(rawCaption, selectedFile.name);caption.textContent =refined || rawCaption || "No caption generated.";status.textContent = "Done.";} catch (error) {console.error(error);status.textContent ="Error: " + (error.message || error);} finally {captionButton.disabled = false;}
index.html+97-42