saltiresoftware commited on
Commit
558c999
·
verified ·
1 Parent(s): da0edcc

Add new app files.

Browse files
Files changed (2) hide show
  1. README.md +15 -16
  2. app.js +25 -66
README.md CHANGED
@@ -8,17 +8,16 @@ app_file: index.html
8
  pinned: false
9
  license: mit
10
  models:
11
- - onnx-community/Qwen2.5-Coder-3B-Instruct
12
  short_description: Build animated CoreGX cams from a short description.
13
  ---
14
 
15
  # CoreGX Cam Studio
16
 
17
- A free Static Hugging Face Space that turns a short description into an
18
- animated CoreGX cam. A public Hugging Face model runs directly in the visitor's
19
- browser through Transformers.js. A small Cloudflare Worker privately adds the
20
- CoreGX key when rendering. It does not run Ollama or require Gradio/Docker
21
- compute.
22
 
23
  ## Deploy
24
 
@@ -26,19 +25,19 @@ compute.
26
  2. In `config.js`, replace the placeholder with the deployed Cloudflare Worker
27
  URL. Do not put the CoreGX key in this repository.
28
  3. Upload the contents of this folder to the root of the Space repository.
29
- 4. In the Worker, set `ALLOWED_ORIGIN` to the Space's direct `.hf.space` URL.
 
 
30
  5. Describe a cam and select **Build cam**.
31
 
32
- No Hugging Face token is needed. The CoreGX key belongs only in the Worker's
33
- `COREGX_API_KEY` secret. Static Space files and values are public to the
34
- visitor's browser.
35
 
36
- The Hugging Face model is `onnx-community/Qwen2.5-Coder-3B-Instruct`. Its quantized
37
- weights download on the first build and are then cached by the browser. The
38
- download is about 2.4 GB with WebGPU (about 3.2 GB for the CPU fallback), so the
39
- first build can take several minutes. To change
40
- the model, edit `BROWSER_MODEL` near the top of `app.js`; the model identifier
41
- is not a secret.
42
 
43
  ## Macro layout
44
 
 
8
  pinned: false
9
  license: mit
10
  models:
11
+ - Qwen/Qwen2.5-Coder-7B-Instruct
12
  short_description: Build animated CoreGX cams from a short description.
13
  ---
14
 
15
  # CoreGX Cam Studio
16
 
17
+ A Static Hugging Face Space that turns a short description into an animated
18
+ CoreGX cam. A Cloudflare Worker privately calls the hosted Hugging Face model
19
+ and CoreGX API. It does not run Ollama or require Gradio/Docker compute, and
20
+ visitors do not download a model or need WebGPU.
 
21
 
22
  ## Deploy
23
 
 
25
  2. In `config.js`, replace the placeholder with the deployed Cloudflare Worker
26
  URL. Do not put the CoreGX key in this repository.
27
  3. Upload the contents of this folder to the root of the Space repository.
28
+ 4. Deploy `cloudflare-worker.js` as the Worker code. In the Worker, set
29
+ `ALLOWED_ORIGIN` to the Space's direct `.hf.space` URL and add the secrets
30
+ `COREGX_API_KEY` and `HF_TOKEN`.
31
  5. Describe a cam and select **Build cam**.
32
 
33
+ The Hugging Face inference token and CoreGX key belong only in the Worker's
34
+ `HF_TOKEN` and `COREGX_API_KEY` secrets. Static Space files and values are
35
+ public to the visitor's browser.
36
 
37
+ The hosted model is `Qwen/Qwen2.5-Coder-7B-Instruct`. To change it, edit
38
+ `HF_MODEL` near the top of `cloudflare-worker.js`; the model identifier is not
39
+ a secret. Hosted inference uses the Hugging Face account associated with the
40
+ Worker's token and is subject to that account's credits and limits.
 
 
41
 
42
  ## Macro layout
43
 
app.js CHANGED
@@ -1,8 +1,5 @@
1
- const BROWSER_MODEL = "onnx-community/Qwen2.5-Coder-3B-Instruct";
2
- const TRANSFORMERS_JS_URL = "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.8.1";
3
  const LOCAL_MODE = window.CAM_STUDIO_LOCAL === true;
4
  const COREGX_PROXY_URL = String(window.CAM_STUDIO_CONFIG?.coregxProxyUrl || "").trim();
5
- let browserGeneratorPromise;
6
 
7
  const TEMPLATES = {
8
  recip_flat: {
@@ -43,10 +40,10 @@ const TEMPLATE_ALIASES = {
43
  };
44
 
45
  const EXAMPLES = {
46
- roller: "Reciprocating roller follower, base radius 20, roller radius 3, offset 2. Rise 8 mm with cycloidal motion over 70 degrees, dwell 80 degrees, then return over 90 degrees. Clockwise.",
47
- flat: "Reciprocating flat follower with a 40 mm base radius and 9 mm offset. Harmonic 6 mm rise over 60 degrees, dwell for 60 degrees, then harmonic return over 60 degrees.",
48
- swing: "Oscillating roller follower below the cam, outside contact, counterclockwise. Start angle 50 degrees, roller radius 5, pivot distance 69, arm length 75. Swing 0.2 radians over 60 degrees, dwell 60 degrees, then return over 60 degrees.",
49
- rocker: "Oscillating flat follower above the cam, clockwise. Start angle 45 degrees, pivot distance 80, flat length 8. Swing 0.18 radians with 3-4-5 motion over 75 degrees, dwell 45 degrees, then return over 75 degrees.",
50
  };
51
 
52
  const NON_REPAIRABLE_ERRORS = [
@@ -284,74 +281,36 @@ async function assembleProgram(name, body) {
284
  return `${followerMacro}\n\n${motionLaws}\n\n${body}\n`;
285
  }
286
 
287
- function modelProgress(progress) {
288
- if (progress?.status !== "progress" || !Number.isFinite(progress.progress)) return;
289
- setStatus(`Loading model… ${Math.round(progress.progress)}%`);
290
- }
291
-
292
- async function createBrowserGenerator() {
293
- setStatus("Loading the browser model…");
294
- const { pipeline, env } = await import(TRANSFORMERS_JS_URL);
295
- env.allowLocalModels = false;
296
-
297
- const options = {
298
- progress_callback: modelProgress,
299
- };
300
-
301
- if (navigator.gpu) {
302
- try {
303
- return await pipeline("text-generation", BROWSER_MODEL, {
304
- ...options,
305
- device: "webgpu",
306
- dtype: "q4f16",
307
- });
308
- } catch (error) {
309
- console.warn("WebGPU model loading failed; using the browser CPU instead.", error);
310
- setStatus("Loading the browser model…");
311
- }
312
- }
313
-
314
- return pipeline("text-generation", BROWSER_MODEL, {
315
- ...options,
316
- device: "wasm",
317
- dtype: "q4",
318
- });
319
- }
320
-
321
- async function getBrowserGenerator() {
322
- if (!browserGeneratorPromise) {
323
- browserGeneratorPromise = createBrowserGenerator().catch((error) => {
324
- browserGeneratorPromise = undefined;
325
- const detail = error instanceof Error ? error.message : String(error);
326
- throw new Error(`Browser model: ${detail}`);
327
- });
328
  }
329
- return browserGeneratorPromise;
 
330
  }
331
 
332
  async function generateBody(messages) {
333
  const systemPrompt = await textFile("system_prompt.txt");
334
- const generator = await getBrowserGenerator();
335
- setStatus("Generating the cam…");
336
- const output = await generator([{ role: "system", content: systemPrompt }, ...messages], {
337
- max_new_tokens: 384,
338
- do_sample: false,
339
- repetition_penalty: 1.03,
 
340
  });
341
-
342
- const generated = output?.[0]?.generated_text;
343
- const content = Array.isArray(generated) ? generated.at(-1)?.content : generated;
344
- if (typeof content !== "string" || !content.trim()) {
345
- throw new Error("The browser model returned an empty response.");
346
  }
347
- return content;
 
 
 
348
  }
349
 
350
  async function renderCoreGX(program) {
351
- if (!/^https:\/\/.+/.test(COREGX_PROXY_URL)) {
352
- throw new Error("Add the Cloudflare Worker URL in config.js.");
353
- }
354
- const response = await fetch(COREGX_PROXY_URL, {
355
  method: "POST",
356
  headers: { "Content-Type": "application/json" },
357
  body: JSON.stringify({ program }),
@@ -446,7 +405,7 @@ async function buildCam() {
446
  return;
447
  } catch (error) {
448
  lastError = error instanceof Error ? error.message : String(error);
449
- const cannotRepair = lastError.startsWith("Browser model:") ||
450
  NON_REPAIRABLE_ERRORS.some((code) => lastError.includes(code));
451
  if (cannotRepair || attempt === 1) throw error;
452
  messages.push(
 
 
 
1
  const LOCAL_MODE = window.CAM_STUDIO_LOCAL === true;
2
  const COREGX_PROXY_URL = String(window.CAM_STUDIO_CONFIG?.coregxProxyUrl || "").trim();
 
3
 
4
  const TEMPLATES = {
5
  recip_flat: {
 
40
  };
41
 
42
  const EXAMPLES = {
43
+ "recip-roller": "Reciprocating roller follower, base radius 20, roller radius 3, offset 2. Rise 8 mm with cycloidal motion over 70 degrees, dwell 80 degrees, then return over 90 degrees. Clockwise.",
44
+ "recip-flat": "Reciprocating flat follower with a 40 mm base radius and 9 mm offset. Harmonic 6 mm rise over 60 degrees, dwell for 60 degrees, then harmonic return over 60 degrees.",
45
+ "osc-roller": "Oscillating roller follower below the cam, outside contact, counterclockwise. Start angle 50 degrees, roller radius 5, pivot distance 69, arm length 75. Swing 0.2 radians over 60 degrees, dwell 60 degrees, then return over 60 degrees.",
46
+ "osc-flat": "Oscillating flat follower above the cam, clockwise. Start angle 45 degrees, pivot distance 80, flat length 8. Swing 0.18 radians with 3-4-5 motion over 75 degrees, dwell 45 degrees, then return over 75 degrees.",
47
  };
48
 
49
  const NON_REPAIRABLE_ERRORS = [
 
281
  return `${followerMacro}\n\n${motionLaws}\n\n${body}\n`;
282
  }
283
 
284
+ function proxyEndpoint(path) {
285
+ if (!/^https:\/\/.+/.test(COREGX_PROXY_URL)) {
286
+ throw new Error("Add the Cloudflare Worker URL in config.js.");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  }
288
+ const base = COREGX_PROXY_URL.endsWith("/") ? COREGX_PROXY_URL : `${COREGX_PROXY_URL}/`;
289
+ return new URL(path.replace(/^\//, ""), base).toString();
290
  }
291
 
292
  async function generateBody(messages) {
293
  const systemPrompt = await textFile("system_prompt.txt");
294
+ setStatus("Running the Hugging Face model…");
295
+ const response = await fetch(proxyEndpoint("generate"), {
296
+ method: "POST",
297
+ headers: { "Content-Type": "application/json" },
298
+ body: JSON.stringify({
299
+ messages: [{ role: "system", content: systemPrompt }, ...messages],
300
+ }),
301
  });
302
+ const result = await response.json().catch(() => ({}));
303
+ if (!response.ok || !result.ok) {
304
+ throw new Error(`Hugging Face: ${String(result.error || `request failed with HTTP ${response.status}.`)}`);
 
 
305
  }
306
+ if (typeof result.content !== "string" || !result.content.trim()) {
307
+ throw new Error("The Hugging Face model returned an empty response.");
308
+ }
309
+ return result.content.trim();
310
  }
311
 
312
  async function renderCoreGX(program) {
313
+ const response = await fetch(proxyEndpoint("render"), {
 
 
 
314
  method: "POST",
315
  headers: { "Content-Type": "application/json" },
316
  body: JSON.stringify({ program }),
 
405
  return;
406
  } catch (error) {
407
  lastError = error instanceof Error ? error.message : String(error);
408
+ const cannotRepair = lastError.startsWith("Hugging Face:") ||
409
  NON_REPAIRABLE_ERRORS.some((code) => lastError.includes(code));
410
  if (cannotRepair || attempt === 1) throw error;
411
  messages.push(