Building an AI Playground with Hugging Face Inference API & Cloudflare Workers
This guide walks through how I built an AI Playground — a browser-based page with 6 AI-powered demos (text-to-image, chat, vision, sentiment analysis, summarization, and translation) — using the Hugging Face Inference API proxied through a Cloudflare Worker. No backend server needed, no API keys exposed to the client.
Architecture Overview
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Browser (Jekyll page)
│
│ POST JSON { model, inputs, parameters }
▼
Cloudflare Worker (hf.yourdomain.workers.dev)
│
│ ── validates origin, model allow-list
│ ── injects HF_API_TOKEN from env secret
│ ── proxies to HF Inference API
▼
Hugging Face Inference API
│
│ returns JSON / image blob
▼
Browser renders result
Why a Cloudflare Worker proxy?
- Secret protection — Your Hugging Face API token stays in the Worker’s environment variables, never sent to the browser.
- CORS control — Only your allowed origins can call the Worker.
- Model allow-list — The Worker rejects requests for any model not in your config, preventing abuse.
- Free tier friendly — Cloudflare Workers free tier gives you 100,000 requests/day.
Part 1: Cloudflare Worker (API Proxy)
1.1 Create the Worker
- Log in to the Cloudflare dashboard
- Go to Workers & Pages → Create Worker
- Name it something like
hf-proxy - Replace the default code with the worker code below
1.2 Add your Hugging Face API Token
- Go to Hugging Face Settings → Access Tokens
- Create a token with Read access (free tier is fine for inference)
- In your Cloudflare Worker settings, go to Settings → Variables and Secrets → Type (set to
Secret) - Add
HF_API_TOKENas an encrypted variable with your token value
1.3 Worker Code
The worker handles three responsibilities: CORS, validation, and proxying.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
// ──────────────────────────────────────────────
// Configuration — single place to update
// ──────────────────────────────────────────────
const CONFIG = {
allowedOrigins: new Set([
"https://linsnotes.com",
"http://localhost:4000",
"http://127.0.0.1:4000",
]),
maxPayloadBytes: 5_000_000,
models: {
"stabilityai/stable-diffusion-xl-base-1.0": { task: "text-to-image" },
"meta-llama/Llama-3.2-1B-Instruct": { task: "chat" },
"google/vit-large-patch16-224": { task: "image-classification" },
"distilbert/distilbert-base-uncased-finetuned-sst-2-english": {
task: "text-classification",
},
"facebook/bart-large-cnn": { task: "summarization" },
"Helsinki-NLP/opus-mt-en-zh": { task: "translation" },
"Helsinki-NLP/opus-mt-zh-en": { task: "translation" },
},
};
// ──────────────────────────────────────────────
// CORS helpers
// ──────────────────────────────────────────────
function getCorsHeaders(origin) {
return {
"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Max-Age": "86400",
};
}
function jsonResponse(data, status, origin) {
return new Response(JSON.stringify(data), {
status,
headers: {
"Content-Type": "application/json",
...(origin ? getCorsHeaders(origin) : {}),
},
});
}
// ──────────────────────────────────────────────
// Validation
// ──────────────────────────────────────────────
function validateOrigin(request) {
const origin = request.headers.get("Origin") || "";
if (!CONFIG.allowedOrigins.has(origin)) return null;
return origin;
}
function parseAndValidateBody(raw) {
if (raw.length > CONFIG.maxPayloadBytes) {
return { error: "Payload too large", status: 413 };
}
let parsed;
try {
parsed = JSON.parse(raw);
} catch {
return { error: "Invalid JSON", status: 400 };
}
const { model, inputs, parameters, messages, type } = parsed; // ← added messages, type
if (!model) {
return { error: "Missing required field: model", status: 400 };
}
// Chat requests use messages instead of inputs
if (type === "chat") {
if (!messages || !Array.isArray(messages)) {
return { error: "Missing required field: messages", status: 400 };
}
} else {
if (inputs === undefined) {
return { error: "Missing required field: inputs", status: 400 };
}
}
if (!CONFIG.models[model]) {
return { error: `Model not allowed: ${model}`, status: 403 };
}
return { model, inputs, parameters, messages, type }; // ← return messages, type
}
// ──────────────────────────────────────────────
// HuggingFace proxies
// ──────────────────────────────────────────────
async function callHuggingFace(model, inputs, parameters, apiToken) {
const url = `https://router.huggingface.co/hf-inference/models/${encodeURIComponent(model)}`;
const payload =
parameters && Object.keys(parameters).length > 0
? { inputs, parameters }
: { inputs };
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${apiToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
return response;
}
// ← NEW: chat completion via OpenAI-compatible HF endpoint
async function callHuggingFaceChat(model, messages, apiToken) {
const response = await fetch(
"https://router.huggingface.co/v1/chat/completions",
{
method: "POST",
headers: {
Authorization: `Bearer ${apiToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
messages,
max_tokens: 512,
temperature: 0.7,
}),
},
);
return response;
}
// ──────────────────────────────────────────────
// Main handler
// ──────────────────────────────────────────────
export default {
async fetch(request, env) {
// 1. CORS preflight
if (request.method === "OPTIONS") {
const origin = request.headers.get("Origin") || "";
if (!CONFIG.allowedOrigins.has(origin)) {
return new Response(null, { status: 403 });
}
return new Response(null, { headers: getCorsHeaders(origin) });
}
// 2. Origin check
const origin = validateOrigin(request);
if (!origin) {
return jsonResponse({ error: "Forbidden" }, 403, null);
}
// 3. Method check
if (request.method !== "POST") {
return jsonResponse({ error: "Method not allowed" }, 405, origin);
}
// 4. Parse + validate body
const raw = await request.text();
const validation = parseAndValidateBody(raw);
if (validation.error) {
return jsonResponse(
{ error: validation.error },
validation.status,
origin,
);
}
const { model, inputs, parameters, messages, type } = validation; // ← added messages, type
// 5a. ← NEW: Chat completion route
if (type === "chat") {
try {
const hfResponse = await callHuggingFaceChat(
model,
messages,
env.HF_API_TOKEN,
);
const data = await hfResponse.json();
return jsonResponse(data, hfResponse.status, origin);
} catch (err) {
console.error("HuggingFace chat request failed:", err);
return jsonResponse({ error: "Upstream request failed" }, 502, origin);
}
}
// 5b. Existing proxy to HuggingFace (images, classification, etc.)
try {
const hfResponse = await callHuggingFace(
model,
inputs,
parameters,
env.HF_API_TOKEN,
);
const contentType =
hfResponse.headers.get("Content-Type") || "application/octet-stream";
const responseBody = await hfResponse.arrayBuffer();
return new Response(responseBody, {
status: hfResponse.status,
headers: {
...getCorsHeaders(origin),
"Content-Type": contentType,
},
});
} catch (err) {
console.error("HuggingFace request failed:", err);
return jsonResponse({ error: "Upstream request failed" }, 502, origin);
}
},
};
Key design decisions:
-
allowedOriginsis aSetfor O(1) lookups — add your production domain and localhost for development. -
modelsacts as an allow-list. Any model not listed here gets a403 Forbidden, so even if someone discovers your worker URL, they can’t use it to run arbitrary models on your HF account.
CORS Helpers
The Access-Control-Max-Age: 86400 tells browsers to cache the preflight response for 24 hours, reducing OPTIONS requests.
Request Validation
Two request shapes are supported:
| Type | Required fields | Used by |
|---|---|---|
| Standard |
model, inputs
|
Image gen, vision, sentiment, summarization, translation |
| Chat |
model, messages, type: "chat"
|
Conversational AI |
Hugging Face Proxy Functions
HF exposes two different endpoints:
-
Inference API (
/hf-inference/models/{model}) — for tasks like image generation, classification, summarization, translation -
OpenAI-compatible (
/v1/chat/completions) — for chat/instruct models, uses the familiarmessagesarray format
Main Request Handler
The standard route returns the raw response (including binary image data for text-to-image), while the chat route always returns JSON.
1.4 Deploy and Test
After deploying, test with curl:
1
2
3
4
5
# Test sentiment analysis
curl -X POST https://hf.yourdomain.workers.dev \
-H "Content-Type: application/json" \
-H "Origin: https://yourdomain.com" \
-d '{"model":"distilbert/distilbert-base-uncased-finetuned-sst-2-english","inputs":"I love this!"}'
You should get back something like:
1
[[{"label":"POSITIVE","score":0.9998},...]]
Part 2: Frontend (Jekyll HTML Page)
The frontend is a single HTML page with inline CSS and JavaScript — no build tools needed. It uses tabs to switch between 6 AI demos.
2.1 Page Setup
Create _pages/ai-playground.html with this front matter:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
---
layout: page
title: AI Playground
permalink: /ai-playground/
compress_html: false
---
<link
href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600&family=Plus+Jakarta+Sans:wght@300;400;500;600;700&display=swap"
rel="stylesheet"
/>
<style>
/* ══════════════════════════════════════════════════════════════
AI PLAYGROUND — STYLES
Inherits from Jekyll Chirpy theme via CSS custom properties.
══════════════════════════════════════════════════════════════ */
#ai-playground {
--bg: var(--main-bg, #faf8f4);
--surface: var(--card-bg, #ffffff);
--border: var(--border-color, #e0d9ce);
--text: var(--text-color, #1e1b16);
--muted: var(--label-color, #7a7265);
--accent: var(--link-color, #b5451b);
--accent-bg: rgba(181, 69, 27, 0.1);
--success: #2d7a3a;
--success-bg: rgba(45, 122, 58, 0.1);
--info: #2a6496;
--info-bg: rgba(42, 100, 150, 0.1);
--danger: #c0392b;
--danger-bg: rgba(192, 57, 43, 0.1);
--mono: "JetBrains Mono", monospace;
--sans: "Plus Jakarta Sans", sans-serif;
--radius: 10px;
--shadow: 0 2px 16px rgba(0, 0, 0, 0.07);
font-family: var(--sans);
color: var(--text);
max-width: 900px;
margin: 0 auto;
padding-bottom: 4rem;
}
[data-mode="dark"] #ai-playground {
--accent-bg: rgba(220, 120, 70, 0.14);
--success-bg: rgba(76, 175, 96, 0.14);
--info-bg: rgba(90, 168, 213, 0.14);
--danger-bg: rgba(231, 76, 60, 0.14);
--success: #4caf60;
--info: #5aa8d5;
}
/* ── Header ── */
.pg-header {
text-align: center;
padding: 1.5rem 1rem 1.2rem;
margin-bottom: 1.5rem;
}
.pg-header .kicker {
font-family: var(--mono);
font-size: 0.7rem;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--accent);
margin-bottom: 0.4rem;
}
.pg-header h2 {
font-size: clamp(1.3rem, 4vw, 1.8rem);
font-weight: 700;
margin: 0 0 0.5rem;
color: var(--text);
}
.pg-header .subtitle {
font-size: 0.85rem;
color: var(--muted);
max-width: 520px;
margin: 0 auto;
line-height: 1.6;
}
/* ── Tab Navigation ──────────────────────────────
Narrow (default): 2 rows of 3 — no scroll ever
Wide (≥ 760px): 1 row of 6
Only one place to change if you add/remove tabs:
adjust flex basis (33.333% = 3 per row) and min-width.
─────────────────────────────────────────────────── */
.pg-tabs {
display: grid;
grid-template-columns: repeat(3, 1fr);
border-bottom: 2px solid var(--border);
margin-bottom: 1.5rem;
}
.pg-tab {
padding: 0.65rem 0.25rem;
font-family: var(--sans);
font-size: 0.75rem;
font-weight: 600;
border: none;
background: transparent;
color: var(--muted);
cursor: pointer;
white-space: normal;
transition:
color 0.2s,
border-color 0.2s;
border-bottom: 2.5px solid transparent;
margin-bottom: -2px;
display: flex;
text-align: center;
align-items: center;
justify-content: center;
gap: 0.35rem;
}
.pg-tab:hover {
color: var(--text);
}
.pg-tab.active {
color: var(--accent);
border-bottom-color: var(--accent);
}
.pg-tab .tab-icon {
font-size: 1rem;
}
/* Wide: single row */
@media (min-width: 760px) {
.pg-tabs {
grid-template-columns: repeat(6, 1fr);
}
}
/* ── Panel Container ── */
.pg-panel {
display: none;
animation: fadeIn 0.3s ease;
}
.pg-panel.active {
display: block;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* ── Shared Card ── */
.pg-card {
background: var(--surface);
border: 1.5px solid var(--border);
border-radius: var(--radius);
padding: 1.5rem;
box-shadow: var(--shadow);
}
/* ── Model Badge ── */
.model-badge {
display: inline-flex;
align-items: center;
gap: 0.35rem;
font-family: var(--mono);
font-size: 0.65rem;
padding: 0.25rem 0.6rem;
border-radius: 20px;
background: var(--info-bg);
color: var(--info);
margin-bottom: 1rem;
font-weight: 500;
}
/* ── Input Areas ── */
.pg-textarea {
width: 100%;
min-height: 100px;
padding: 0.8rem 1rem;
border: 1.5px solid var(--border);
border-radius: var(--radius);
background: var(--bg);
color: var(--text);
font-family: var(--sans);
font-size: 0.85rem;
resize: vertical;
transition: border-color 0.2s;
box-sizing: border-box;
}
.pg-textarea:focus {
outline: none;
border-color: var(--accent);
}
.pg-textarea::placeholder {
color: var(--muted);
}
.pg-input {
width: 100%;
padding: 0.7rem 1rem;
border: 1.5px solid var(--border);
border-radius: var(--radius);
background: var(--bg);
color: var(--text);
font-family: var(--sans);
font-size: 0.85rem;
transition: border-color 0.2s;
box-sizing: border-box;
}
.pg-input:focus {
outline: none;
border-color: var(--accent);
}
/* ── Buttons ── */
.pg-btn {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.6rem 1.4rem;
border: none;
border-radius: var(--radius);
background: var(--accent);
color: #fff;
font-family: var(--sans);
font-size: 0.82rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s;
margin-top: 0.8rem;
}
.pg-btn:hover {
filter: brightness(1.1);
transform: translateY(-1px);
}
.pg-btn:active {
transform: translateY(0);
}
.pg-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
filter: none;
}
/* ── Output / Result ── */
.pg-result {
margin-top: 1.2rem;
padding: 1rem;
border: 1.5px solid var(--border);
border-radius: var(--radius);
background: var(--bg);
min-height: 60px;
font-size: 0.85rem;
line-height: 1.7;
white-space: pre-wrap;
word-break: break-word;
}
.pg-result.empty {
color: var(--muted);
font-style: italic;
display: flex;
align-items: center;
justify-content: center;
min-height: 80px;
}
/* ── Loading Spinner ── */
.pg-spinner {
display: inline-block;
width: 18px;
height: 18px;
border: 2.5px solid var(--border);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.7s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* ── Status Messages ── */
.pg-status {
font-size: 0.75rem;
margin-top: 0.5rem;
color: var(--muted);
min-height: 1.2em;
}
.pg-status.error {
color: var(--danger);
}
.pg-status.success {
color: var(--success);
}
/* ── Image Output ── */
.pg-img-output {
margin-top: 1.2rem;
text-align: center;
}
.pg-img-output img {
max-width: 100%;
border-radius: var(--radius);
border: 1.5px solid var(--border);
box-shadow: var(--shadow);
}
/* ── Image Upload / Drop Zone ── */
.pg-dropzone {
border: 2px dashed var(--border);
border-radius: var(--radius);
padding: 2rem;
text-align: center;
cursor: pointer;
transition: all 0.2s;
background: var(--bg);
color: var(--muted);
font-size: 0.85rem;
position: relative;
}
.pg-dropzone:hover,
.pg-dropzone.dragover {
border-color: var(--accent);
background: var(--accent-bg);
color: var(--accent);
}
.pg-dropzone input[type="file"] {
position: absolute;
inset: 0;
opacity: 0;
cursor: pointer;
}
.pg-dropzone .drop-icon {
font-size: 2rem;
display: block;
margin-bottom: 0.5rem;
}
.pg-or-divider {
text-align: center;
color: var(--text-muted);
font-size: 0.8rem;
margin: 0.5rem 0;
}
.pg-preview-img {
max-width: 300px;
max-height: 250px;
border-radius: var(--radius);
margin-top: 1rem;
border: 1.5px solid var(--border);
}
/* ── Sentiment Bars ── */
.sentiment-bar-container {
margin-top: 1rem;
}
.sentiment-row {
display: flex;
align-items: center;
gap: 0.8rem;
margin-bottom: 0.6rem;
}
.sentiment-label {
font-family: var(--mono);
font-size: 0.75rem;
font-weight: 500;
width: 90px;
text-align: right;
text-transform: uppercase;
flex-shrink: 0;
}
.sentiment-bar-track {
flex: 1;
height: 26px;
background: var(--bg);
border-radius: 13px;
border: 1px solid var(--border);
overflow: hidden;
position: relative;
}
.sentiment-bar-fill {
height: 100%;
border-radius: 13px;
transition: width 0.8s cubic-bezier(0.25, 0.8, 0.25, 1);
display: flex;
align-items: center;
justify-content: flex-end;
padding-right: 8px;
font-family: var(--mono);
font-size: 0.68rem;
font-weight: 600;
color: #fff;
min-width: 0;
}
.sentiment-bar-fill.positive {
background: linear-gradient(90deg, #27ae60, #2ecc71);
}
.sentiment-bar-fill.negative {
background: linear-gradient(90deg, #c0392b, #e74c3c);
}
/* ── Classification Labels ── */
.classify-results {
margin-top: 1rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.classify-row {
display: flex;
align-items: center;
gap: 0.8rem;
}
.classify-label {
font-family: var(--mono);
font-size: 0.72rem;
font-weight: 500;
width: 140px;
text-align: right;
flex-shrink: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.classify-bar-track {
flex: 1;
height: 22px;
background: var(--bg);
border-radius: 11px;
border: 1px solid var(--border);
overflow: hidden;
}
.classify-bar-fill {
height: 100%;
border-radius: 11px;
background: linear-gradient(90deg, var(--accent), #e07b4f);
transition: width 0.8s cubic-bezier(0.25, 0.8, 0.25, 1);
display: flex;
align-items: center;
justify-content: flex-end;
padding-right: 6px;
font-family: var(--mono);
font-size: 0.62rem;
font-weight: 600;
color: #fff;
min-width: 0;
}
/* ── Chat Interface ── */
.chat-messages {
max-height: 400px;
overflow-y: auto;
padding: 1rem;
border: 1.5px solid var(--border);
border-radius: var(--radius);
background: var(--bg);
margin-bottom: 0.8rem;
display: flex;
flex-direction: column;
gap: 0.8rem;
}
.chat-bubble {
max-width: 80%;
padding: 0.7rem 1rem;
border-radius: 14px;
font-size: 0.84rem;
line-height: 1.6;
word-break: break-word;
white-space: pre-wrap;
}
.chat-bubble.user {
align-self: flex-end;
background: var(--accent);
color: #fff;
border-bottom-right-radius: 4px;
}
.chat-bubble.assistant {
align-self: flex-start;
background: var(--surface);
border: 1px solid var(--border);
color: var(--text);
border-bottom-left-radius: 4px;
}
.chat-bubble.thinking {
align-self: flex-start;
background: var(--surface);
border: 1px solid var(--border);
color: var(--muted);
font-style: italic;
}
.chat-input-row {
display: flex;
gap: 0.5rem;
}
.chat-input-row .pg-input {
flex: 1;
}
.chat-input-row .pg-btn {
margin-top: 0;
flex-shrink: 0;
}
/* ── Info Note ── */
.pg-note {
font-size: 0.72rem;
color: var(--muted);
margin-top: 0.8rem;
line-height: 1.5;
padding: 0.6rem 0.8rem;
background: var(--info-bg);
border-radius: var(--radius);
border-left: 3px solid var(--info);
}
/* ── Layout helpers ── */
.pg-label {
font-size: 0.78rem;
font-weight: 600;
margin-bottom: 0.4rem;
display: block;
color: var(--text);
}
.pg-section {
margin-bottom: 1rem;
}
/* ── Example Prompts ── */
.pg-examples {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
margin-top: 0.5rem;
}
.pg-examples-label {
font-size: 0.7rem;
color: var(--muted);
width: 100%;
margin-bottom: 0.1rem;
}
.pg-example-chip {
font-family: var(--sans);
font-size: 0.72rem;
padding: 0.3rem 0.7rem;
border-radius: 20px;
border: 1px solid var(--border);
background: var(--bg);
color: var(--muted);
cursor: pointer;
transition: all 0.2s;
white-space: nowrap;
}
.pg-example-chip:hover {
border-color: var(--accent);
color: var(--accent);
background: var(--accent-bg);
}
/* ── Character Counter ── */
.pg-char-count {
font-family: var(--mono);
font-size: 0.65rem;
color: var(--muted);
text-align: right;
margin-top: 0.25rem;
}
.pg-char-count.warn {
color: var(--danger);
}
/* ── Chat Controls ── */
.chat-controls {
display: flex;
justify-content: flex-end;
margin-bottom: 0.5rem;
}
.pg-btn-ghost {
font-family: var(--sans);
font-size: 0.7rem;
font-weight: 500;
padding: 0.25rem 0.6rem;
border: 1px solid var(--border);
border-radius: 6px;
background: transparent;
color: var(--muted);
cursor: pointer;
transition: all 0.2s;
}
.pg-btn-ghost:hover {
border-color: var(--danger);
color: var(--danger);
background: var(--danger-bg);
}
/* ── Responsive ── */
@media (max-width: 600px) {
#ai-playground {
padding-left: 0.5rem;
padding-right: 0.5rem;
}
.pg-card {
padding: 1rem;
}
.pg-tab {
padding: 0.6rem 0.7rem;
font-size: 0.72rem;
}
.chat-bubble {
max-width: 90%;
}
.sentiment-label,
.classify-label {
width: 70px;
font-size: 0.65rem;
}
.pg-example-chip {
font-size: 0.66rem;
padding: 0.25rem 0.55rem;
}
}
</style>
<div id="ai-playground">
<!-- Header -->
<div class="pg-header">
<div class="kicker">Hugging Face Inference API</div>
<h2>AI Playground</h2>
<p class="subtitle">
Experiment with 6 state-of-the-art AI models directly in your browser. All
inference runs on Hugging Face's cloud — no data is stored.
</p>
</div>
<!-- Tabs -->
<div class="pg-tabs" role="tablist">
<button class="pg-tab active" data-tab="text2img" role="tab">
<span class="tab-icon">🎨</span> Text to Image
</button>
<button class="pg-tab" data-tab="chat" role="tab">
<span class="tab-icon">💬</span> AI Chat
</button>
<button class="pg-tab" data-tab="vision" role="tab">
<span class="tab-icon">👁</span> Vision
</button>
<button class="pg-tab" data-tab="sentiment" role="tab">
<span class="tab-icon">📊</span> Sentiment
</button>
<button class="pg-tab" data-tab="summarize" role="tab">
<span class="tab-icon">📝</span> Summarize
</button>
<button class="pg-tab" data-tab="translate" role="tab">
<span class="tab-icon">🌐</span> Translate
</button>
</div>
<!-- ═══════════════════════════════════════════
PANEL 1: Text-to-Image
═══════════════════════════════════════════ -->
<div class="pg-panel active" data-panel="text2img">
<div class="pg-card">
<span class="model-badge"
>🤗 stabilityai/stable-diffusion-xl-base-1.0</span
>
<div class="pg-section">
<label class="pg-label">Describe the image you want to generate</label>
<textarea
class="pg-textarea"
id="img-prompt"
placeholder="Describe your image in detail — style, subject, lighting, mood..."
rows="3"
></textarea>
<div class="pg-examples">
<span class="pg-examples-label">Try an example:</span>
<button
class="pg-example-chip"
data-target="img-prompt"
data-text="A cat astronaut floating in space with Earth in the background, digital art, vibrant colors"
>
Cat astronaut
</button>
<button
class="pg-example-chip"
data-target="img-prompt"
data-text="A cozy Japanese ramen shop at night, rain outside, warm lantern glow, watercolor style"
>
Ramen shop
</button>
<button
class="pg-example-chip"
data-target="img-prompt"
data-text="Minimalist geometric mountains at sunset, flat design, pastel gradients"
>
Geometric mountains
</button>
</div>
</div>
<button class="pg-btn" id="img-btn" onclick="generateImage()">
<span>Generate Image</span>
</button>
<div class="pg-note">
Generation may take 10–30 seconds. The model runs on HF's free inference
tier.
</div>
<div id="img-status" class="pg-status"></div>
<div id="img-output" class="pg-img-output"></div>
</div>
</div>
<!-- ═══════════════════════════════════════════
PANEL 2: AI Chat
═══════════════════════════════════════════ -->
<div class="pg-panel" data-panel="chat">
<div class="pg-card">
<span class="model-badge"
>🤗 meta-llama/Llama-3.2-1B-Instruct</span
>
<div class="chat-controls">
<button class="pg-btn-ghost" id="chat-clear-btn" onclick="clearChat()">
Clear chat
</button>
</div>
<div class="chat-messages" id="chat-messages">
<div class="chat-bubble assistant">
Hello! I'm a helpful AI assistant. Ask me anything.
</div>
</div>
<div class="chat-input-row">
<input
class="pg-input"
id="chat-input"
type="text"
placeholder="Type your message..."
onkeydown="
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
sendChat();
}
"
/>
<button
class="pg-btn"
id="chat-btn"
onclick="sendChat()"
style="margin-top: 0"
>
Send
</button>
</div>
<div class="pg-examples" style="margin-top: 0.6rem">
<span class="pg-examples-label">Try asking:</span>
<button
class="pg-example-chip"
data-target="chat-input"
data-text="What is the difference between machine learning and deep learning?"
>
ML vs deep learning
</button>
<button
class="pg-example-chip"
data-target="chat-input"
data-text="Explain quantum computing in simple terms"
>
Quantum computing
</button>
<button
class="pg-example-chip"
data-target="chat-input"
data-text="Give me 3 tips for writing clean code"
>
Clean code tips
</button>
</div>
<div class="pg-note">
Conversation context is maintained within this session. Responses come
from Llama-3.2-1B.
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════
PANEL 3: Image Classification (Vision)
═══════════════════════════════════════════ -->
<div class="pg-panel" data-panel="vision">
<div class="pg-card">
<span class="model-badge">🤗 google/vit-large-patch16-224</span>
<div class="pg-section">
<label class="pg-label">Upload an image to classify</label>
<div class="pg-dropzone" id="vision-dropzone">
<span class="drop-icon">📷</span>
<span>Drag & drop, paste from clipboard, or click to browse</span>
<input
type="file"
accept="image/*"
id="vision-file"
onchange="handleVisionFile(this)"
/>
</div>
</div>
<div class="pg-or-divider">— or —</div>
<div class="pg-section">
<label class="pg-label">Paste an image URL</label>
<input
class="pg-input"
id="vision-url"
type="url"
placeholder="https://example.com/photo.jpg"
oninput="handleVisionUrl(this.value)"
/>
</div>
<button class="pg-btn" id="vision-btn" onclick="classifyImage()" disabled>
Classify Image
</button>
<div class="pg-note">
The model identifies objects in photos — try uploading a picture of an
animal, food, vehicle, or everyday object.
</div>
<div id="vision-status" class="pg-status"></div>
<div id="vision-output" class="classify-results"></div>
</div>
</div>
<!-- ═══════════════════════════════════════════
PANEL 4: Sentiment Analysis
═══════════════════════════════════════════ -->
<div class="pg-panel" data-panel="sentiment">
<div class="pg-card">
<span class="model-badge"
>🤗 distilbert-base-uncased-finetuned-sst-2-english</span
>
<div class="pg-section">
<label class="pg-label">Enter text to analyze sentiment</label>
<textarea
class="pg-textarea"
id="sentiment-input"
placeholder="Type or paste any English text — a review, tweet, comment..."
rows="3"
></textarea>
<div class="pg-examples">
<span class="pg-examples-label">Try an example:</span>
<button
class="pg-example-chip"
data-target="sentiment-input"
data-text="I absolutely love this product! It exceeded all my expectations and the quality is outstanding."
>
Positive review
</button>
<button
class="pg-example-chip"
data-target="sentiment-input"
data-text="The service was terrible, I waited 45 minutes and my order was completely wrong."
>
Negative review
</button>
<button
class="pg-example-chip"
data-target="sentiment-input"
data-text="The movie was okay I guess, nothing special but not the worst I've seen."
>
Mixed feelings
</button>
</div>
</div>
<button class="pg-btn" id="sentiment-btn" onclick="analyzeSentiment()">
Analyze Sentiment
</button>
<div id="sentiment-status" class="pg-status"></div>
<div id="sentiment-output" class="sentiment-bar-container"></div>
</div>
</div>
<!-- ═══════════════════════════════════════════
PANEL 5: Summarization
═══════════════════════════════════════════ -->
<div class="pg-panel" data-panel="summarize">
<div class="pg-card">
<span class="model-badge">🤗 facebook/bart-large-cnn</span>
<div class="pg-section">
<label class="pg-label"
>Paste an article or long text to summarize</label
>
<textarea
class="pg-textarea"
id="summary-input"
placeholder="Paste a news article, essay, or any long text here (at least a few sentences)..."
rows="6"
oninput="updateCharCount('summary-input', 'summary-charcount', 5000)"
></textarea>
<div class="pg-char-count" id="summary-charcount">
0 / 5,000 characters
</div>
<div class="pg-examples">
<span class="pg-examples-label">Try an example:</span>
<button
class="pg-example-chip"
data-target="summary-input"
data-text="Artificial intelligence has transformed the way we interact with technology. From virtual assistants like Siri and Alexa to recommendation algorithms on Netflix and Spotify, AI is embedded in our daily lives. Machine learning, a subset of AI, allows systems to learn from data without being explicitly programmed. Deep learning, which uses neural networks with many layers, has achieved breakthroughs in image recognition, natural language processing, and game playing. However, the rapid advancement of AI also raises concerns about job displacement, privacy, algorithmic bias, and the need for regulation. Researchers and policymakers are working to ensure that AI development remains beneficial and aligned with human values."
>
AI overview article
</button>
</div>
</div>
<button class="pg-btn" id="summary-btn" onclick="summarizeText()">
Summarize
</button>
<div id="summary-status" class="pg-status"></div>
<div id="summary-output" class="pg-result empty">
Summary will appear here
</div>
</div>
</div>
<!-- ═══════════════════════════════════════════
PANEL 6: Translation (EN ↔ ZH)
═══════════════════════════════════════════ -->
<div class="pg-panel" data-panel="translate">
<div class="pg-card">
<span class="model-badge" id="translate-model-badge"
>🤗 Helsinki-NLP/opus-mt-en-zh</span
>
<div class="pg-section">
<label class="pg-label">
Direction:
<select
id="translate-dir"
onchange="updateTranslateDirection()"
style="
font-family: var(--sans);
font-size: 0.82rem;
padding: 0.3rem 0.5rem;
border: 1.5px solid var(--border);
border-radius: 6px;
background: var(--bg);
color: var(--text);
margin-left: 0.4rem;
"
>
<option value="en-zh">English → Chinese</option>
<option value="zh-en">Chinese → English</option>
</select>
</label>
</div>
<div class="pg-section">
<label class="pg-label" id="translate-src-label">English text</label>
<textarea
class="pg-textarea"
id="translate-input"
placeholder="Enter text to translate..."
rows="3"
></textarea>
<div class="pg-examples" id="translate-examples">
<span class="pg-examples-label">Try an example:</span>
<button
class="pg-example-chip"
data-target="translate-input"
data-text="The quick brown fox jumps over the lazy dog."
>
Quick brown fox
</button>
<button
class="pg-example-chip"
data-target="translate-input"
data-text="Technology is reshaping the future of education around the world."
>
Tech in education
</button>
</div>
</div>
<button class="pg-btn" id="translate-btn" onclick="translateText()">
Translate
</button>
<div id="translate-status" class="pg-status"></div>
<div class="pg-section" style="margin-top: 1rem">
<label class="pg-label" id="translate-tgt-label"
>Chinese translation</label
>
<div id="translate-output" class="pg-result empty">
Translation will appear here
</div>
</div>
</div>
</div>
</div>
<script>
(function () {
"use strict";
// ── Config ──
const WORKER_URL = "https://hf.kuibin.workers.dev";
const MODELS = {
text2img: "stabilityai/stable-diffusion-xl-base-1.0",
chat: "meta-llama/Llama-3.2-1B-Instruct",
vision: "google/vit-large-patch16-224",
sentiment: "distilbert/distilbert-base-uncased-finetuned-sst-2-english",
summarize: "facebook/bart-large-cnn",
translateEnZh: "Helsinki-NLP/opus-mt-en-zh",
translateZhEn: "Helsinki-NLP/opus-mt-zh-en",
};
// ── Tab Switching ──
const tabs = document.querySelectorAll(".pg-tab");
const panels = document.querySelectorAll(".pg-panel");
tabs.forEach((tab) => {
tab.addEventListener("click", () => {
tabs.forEach((t) => t.classList.remove("active"));
panels.forEach((p) => p.classList.remove("active"));
tab.classList.add("active");
document.querySelector(`[data-panel="${tab.dataset.tab}"]`).classList.add("active");
});
});
// ── Example Chips — fill input on click ──
document.querySelectorAll(".pg-example-chip").forEach((chip) => {
chip.addEventListener("click", () => {
const target = document.getElementById(chip.dataset.target);
if (!target) return;
target.value = chip.dataset.text;
target.focus();
target.dispatchEvent(new Event("input", { bubbles: true }));
});
});
// ── Character Counter ──
window.updateCharCount = function (inputId, counterId, max) {
const len = document.getElementById(inputId).value.length;
const counter = document.getElementById(counterId);
counter.textContent = `${len.toLocaleString()} / ${max.toLocaleString()} characters`;
counter.classList.toggle("warn", len > max);
};
// ── Drag & Drop for Vision ──
const dropzone = document.getElementById("vision-dropzone");
["dragenter", "dragover"].forEach((e) =>
dropzone.addEventListener(e, (ev) => { ev.preventDefault(); dropzone.classList.add("dragover"); })
);
["dragleave", "drop"].forEach((e) =>
dropzone.addEventListener(e, () => dropzone.classList.remove("dragover"))
);
dropzone.addEventListener("drop", (ev) => {
ev.preventDefault();
const file = ev.dataTransfer.files[0];
if (file && file.type.startsWith("image/")) {
document.getElementById("vision-file").files = ev.dataTransfer.files;
handleVisionFile(document.getElementById("vision-file"));
}
});
// Clipboard paste — works anywhere on the page when vision panel is active
document.addEventListener("paste", (ev) => {
if (!document.querySelector('[data-panel="vision"].active')) return;
const items = ev.clipboardData?.items;
if (!items) return;
for (const item of items) {
if (item.type.startsWith("image/")) {
const file = item.getAsFile();
const dt = new DataTransfer();
dt.items.add(file);
const fakeInput = { files: dt.files };
handleVisionFile(fakeInput);
break;
}
}
});
// ── API Helper ──
async function queryWorker(model, inputs, parameters, isBlob) {
const res = await fetch(WORKER_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, inputs, parameters }),
});
if (!res.ok) {
let errMsg = `Error ${res.status}`;
try {
const errBody = await res.text();
const parsed = JSON.parse(errBody);
errMsg = parsed.error || parsed.message || errBody || errMsg;
} catch (_) {}
throw new Error(errMsg);
}
return isBlob ? res.blob() : res.json();
}
// Chat completion using OpenAI-compatible HF endpoint
async function queryWorkerChat(messages) {
const res = await fetch(WORKER_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model: MODELS.chat, messages, type: "chat" }),
});
if (!res.ok) {
let errMsg = `Error ${res.status}`;
try {
const errBody = await res.text();
const parsed = JSON.parse(errBody);
errMsg = parsed.error || parsed.message || errBody || errMsg;
} catch (_) {}
throw new Error(errMsg);
}
const data = await res.json();
return data.choices[0].message.content;
}
async function queryWorkerRaw(model, binaryData) {
const res = await fetch(WORKER_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model,
inputs: Array.from(new Uint8Array(binaryData)),
}),
});
if (!res.ok) {
let errMsg = `Error ${res.status}`;
try { errMsg = (await res.json()).error || errMsg; } catch (_) {}
throw new Error(errMsg);
}
return res.json();
}
// ── Loading / Status helpers ──
function setLoading(btnId, statusId, loading, msg) {
const btn = document.getElementById(btnId);
const status = document.getElementById(statusId);
btn.disabled = loading;
if (loading) {
btn.dataset.origText = btn.innerHTML;
btn.innerHTML = '<span class="pg-spinner"></span> Processing...';
status.className = "pg-status";
status.textContent = msg || "Sending request to model...";
} else {
btn.innerHTML = btn.dataset.origText || btn.innerHTML;
// Don't clear status — let success/error messages persist
}
}
function showError(statusId, msg) {
const el = document.getElementById(statusId);
el.className = "pg-status error";
el.textContent = msg;
}
function showSuccess(statusId, msg) {
const el = document.getElementById(statusId);
el.className = "pg-status success";
el.textContent = msg;
}
function clearStatus(statusId) {
const el = document.getElementById(statusId);
el.className = "pg-status";
el.textContent = "";
}
// ── Sanitize text for safe HTML insertion ──
function escapeHtml(str) {
const div = document.createElement("div");
div.textContent = str;
return div.innerHTML;
}
// ══════════════════════════════════════
// 1. TEXT-TO-IMAGE
// ══════════════════════════════════════
window.generateImage = async function () {
const prompt = document.getElementById("img-prompt").value.trim();
if (!prompt) return;
const output = document.getElementById("img-output");
output.innerHTML = "";
clearStatus("img-status");
setLoading("img-btn", "img-status", true, "Generating image... this may take 10–30s");
try {
const blob = await queryWorker(MODELS.text2img, prompt, {}, true);
const url = URL.createObjectURL(blob);
const img = document.createElement("img");
img.src = url;
img.alt = "AI-generated image";
output.appendChild(img);
showSuccess("img-status", "Image generated successfully");
} catch (err) {
showError("img-status", "Failed: " + err.message);
} finally {
setLoading("img-btn", "img-status", false);
}
};
// ══════════════════════════════════════
// 2. AI CHAT
// ══════════════════════════════════════
let chatHistory = [];
window.clearChat = function () {
chatHistory = [];
const messagesEl = document.getElementById("chat-messages");
messagesEl.innerHTML = '<div class="chat-bubble assistant">Hello! I\'m a helpful AI assistant. Ask me anything.</div>';
};
window.sendChat = async function () {
const input = document.getElementById("chat-input");
const msg = input.value.trim();
if (!msg) return;
input.value = "";
const messagesEl = document.getElementById("chat-messages");
// Add user bubble
const userBubble = document.createElement("div");
userBubble.className = "chat-bubble user";
userBubble.textContent = msg;
messagesEl.appendChild(userBubble);
// Add thinking bubble
const thinkBubble = document.createElement("div");
thinkBubble.className = "chat-bubble thinking";
thinkBubble.innerHTML = '<span class="pg-spinner"></span> Thinking...';
messagesEl.appendChild(thinkBubble);
messagesEl.scrollTop = messagesEl.scrollHeight;
// Build conversation in OpenAI messages format
chatHistory.push({ role: "user", content: msg });
const systemPrompt = "You are a helpful, friendly AI assistant. Give concise but informative answers.";
const messages = [
{ role: "system", content: systemPrompt },
...chatHistory.slice(-12),
];
const btn = document.getElementById("chat-btn");
btn.disabled = true;
try {
const reply = await queryWorkerChat(messages);
chatHistory.push({ role: "assistant", content: reply });
thinkBubble.className = "chat-bubble assistant";
thinkBubble.textContent = reply;
} catch (err) {
thinkBubble.className = "chat-bubble assistant";
thinkBubble.textContent = "Sorry, something went wrong: " + err.message;
} finally {
btn.disabled = false;
messagesEl.scrollTop = messagesEl.scrollHeight;
input.focus();
}
};
// ══════════════════════════════════════
// 3. IMAGE CLASSIFICATION
// ══════════════════════════════════════
let visionFileData = null;
window.handleVisionFile = function (input) {
const file = input.files[0];
if (!file) return;
if (file.size > 4 * 1024 * 1024) {
showError("vision-status", "Image too large — please use an image under 4MB.");
return;
}
let preview = document.getElementById("vision-preview");
if (!preview) {
preview = document.createElement("img");
preview.id = "vision-preview";
preview.className = "pg-preview-img";
document.getElementById("vision-dropzone").insertAdjacentElement("afterend", preview);
}
const reader = new FileReader();
reader.onload = (e) => {
visionFileData = e.target.result; // base64 data URL — HF accepts this directly
preview.src = visionFileData;
preview.style.display = "block";
document.getElementById("vision-url").value = "";
document.getElementById("vision-btn").disabled = false;
clearStatus("vision-status");
};
reader.readAsDataURL(file);
};
window.handleVisionUrl = function (url) {
const trimmed = url.trim();
if (!trimmed) {
visionFileData = null;
document.getElementById("vision-btn").disabled = true;
const preview = document.getElementById("vision-preview");
if (preview) { preview.src = ""; preview.style.display = "none"; }
return;
}
let preview = document.getElementById("vision-preview");
if (!preview) {
preview = document.createElement("img");
preview.id = "vision-preview";
preview.className = "pg-preview-img";
document.getElementById("vision-dropzone").insertAdjacentElement("afterend", preview);
}
preview.onerror = () => {
showError("vision-status", "Could not load image — check the URL is a direct image link.");
document.getElementById("vision-btn").disabled = true;
visionFileData = null;
};
preview.onload = () => {
visionFileData = trimmed;
document.getElementById("vision-btn").disabled = false;
clearStatus("vision-status");
};
preview.src = trimmed;
preview.style.display = "block";
};
window.classifyImage = async function () {
if (!visionFileData) return;
const output = document.getElementById("vision-output");
output.innerHTML = "";
clearStatus("vision-status");
setLoading("vision-btn", "vision-status", true, "Classifying image...");
try {
const data = await queryWorker(MODELS.vision, visionFileData, {});
const results = Array.isArray(data) ? data : [data];
const top5 = results.slice(0, 5);
output.innerHTML = top5.map((r, i) => {
const pct = (r.score * 100).toFixed(1);
const delay = i * 100;
return `
<div class="classify-row">
<span class="classify-label" title="${escapeHtml(r.label)}">${escapeHtml(r.label)}</span>
<div class="classify-bar-track">
<div class="classify-bar-fill" style="width: 0%; transition-delay: ${delay}ms"
data-width="${pct}%">${pct}%</div>
</div>
</div>`;
}).join("");
requestAnimationFrame(() => {
requestAnimationFrame(() => {
output.querySelectorAll(".classify-bar-fill").forEach((bar) => {
bar.style.width = bar.dataset.width;
});
});
});
showSuccess("vision-status", "Classification complete");
} catch (err) {
showError("vision-status", "Failed: " + err.message);
} finally {
setLoading("vision-btn", "vision-status", false);
}
};
// ══════════════════════════════════════
// 4. SENTIMENT ANALYSIS
// ══════════════════════════════════════
window.analyzeSentiment = async function () {
const text = document.getElementById("sentiment-input").value.trim();
if (!text) return;
const output = document.getElementById("sentiment-output");
output.innerHTML = "";
clearStatus("sentiment-status");
setLoading("sentiment-btn", "sentiment-status", true, "Analyzing sentiment...");
try {
const data = await queryWorker(MODELS.sentiment, text);
const results = Array.isArray(data[0]) ? data[0] : data;
output.innerHTML = results.map((r, i) => {
const pct = (r.score * 100).toFixed(1);
const label = r.label.toUpperCase();
const cls = label === "POSITIVE" ? "positive" : "negative";
const delay = i * 150;
return `
<div class="sentiment-row">
<span class="sentiment-label">${escapeHtml(label)}</span>
<div class="sentiment-bar-track">
<div class="sentiment-bar-fill ${cls}" style="width: 0%; transition-delay: ${delay}ms"
data-width="${pct}%">${pct}%</div>
</div>
</div>`;
}).join("");
requestAnimationFrame(() => {
requestAnimationFrame(() => {
output.querySelectorAll(".sentiment-bar-fill").forEach((bar) => {
bar.style.width = bar.dataset.width;
});
});
});
showSuccess("sentiment-status", "Analysis complete");
} catch (err) {
showError("sentiment-status", "Failed: " + err.message);
} finally {
setLoading("sentiment-btn", "sentiment-status", false);
}
};
// ══════════════════════════════════════
// 5. SUMMARIZATION
// ══════════════════════════════════════
window.summarizeText = async function () {
const text = document.getElementById("summary-input").value.trim();
if (!text) return;
if (text.length < 50) {
showError("summary-status", "Please enter more text — the model needs at least a few sentences to summarize.");
return;
}
const output = document.getElementById("summary-output");
output.className = "pg-result empty";
output.textContent = "Summarizing...";
clearStatus("summary-status");
setLoading("summary-btn", "summary-status", true, "Generating summary...");
try {
const data = await queryWorker(MODELS.summarize, text, {
max_length: 150,
min_length: 30,
});
const summary = data[0]?.summary_text || "Could not generate summary.";
output.className = "pg-result";
output.textContent = summary;
showSuccess("summary-status", "Summary generated");
} catch (err) {
output.className = "pg-result empty";
output.textContent = "Summary will appear here";
showError("summary-status", "Failed: " + err.message);
} finally {
setLoading("summary-btn", "summary-status", false);
}
};
// ══════════════════════════════════════
// 6. TRANSLATION
// ══════════════════════════════════════
window.updateTranslateDirection = function () {
const dir = document.getElementById("translate-dir").value;
const srcLabel = document.getElementById("translate-src-label");
const tgtLabel = document.getElementById("translate-tgt-label");
const badge = document.getElementById("translate-model-badge");
const input = document.getElementById("translate-input");
const examples = document.getElementById("translate-examples");
if (dir === "en-zh") {
srcLabel.textContent = "English text";
tgtLabel.textContent = "Chinese translation";
badge.innerHTML = "🤗 Helsinki-NLP/opus-mt-en-zh";
input.placeholder = "Enter English text to translate...";
examples.innerHTML = `
<span class="pg-examples-label">Try an example:</span>
<button class="pg-example-chip" data-target="translate-input" data-text="The quick brown fox jumps over the lazy dog.">Quick brown fox</button>
<button class="pg-example-chip" data-target="translate-input" data-text="Technology is reshaping the future of education around the world.">Tech in education</button>
`;
} else {
srcLabel.textContent = "Chinese text";
tgtLabel.textContent = "English translation";
badge.innerHTML = "🤗 Helsinki-NLP/opus-mt-zh-en";
input.placeholder = "输入中文文本...";
examples.innerHTML = `
<span class="pg-examples-label">试试这些例子:</span>
<button class="pg-example-chip" data-target="translate-input" data-text="人工智能正在改变我们的生活方式。">AI 改变生活</button>
<button class="pg-example-chip" data-target="translate-input" data-text="今天的天气非常好,适合出去散步。">天气很好</button>
`;
}
// Re-bind example chips for new buttons
examples.querySelectorAll(".pg-example-chip").forEach((chip) => {
chip.addEventListener("click", () => {
const target = document.getElementById(chip.dataset.target);
if (!target) return;
target.value = chip.dataset.text;
target.focus();
});
});
const output = document.getElementById("translate-output");
output.className = "pg-result empty";
output.textContent = "Translation will appear here";
clearStatus("translate-status");
};
window.translateText = async function () {
const text = document.getElementById("translate-input").value.trim();
if (!text) return;
const dir = document.getElementById("translate-dir").value;
const model = dir === "en-zh" ? MODELS.translateEnZh : MODELS.translateZhEn;
const output = document.getElementById("translate-output");
output.className = "pg-result empty";
output.textContent = "Translating...";
clearStatus("translate-status");
setLoading("translate-btn", "translate-status", true, "Translating text...");
try {
const data = await queryWorker(model, text);
const translation = data[0]?.translation_text || "Could not translate.";
output.className = "pg-result";
output.textContent = translation;
showSuccess("translate-status", "Translation complete");
} catch (err) {
output.className = "pg-result empty";
output.textContent = "Translation will appear here";
showError("translate-status", "Failed: " + err.message);
} finally {
setLoading("translate-btn", "translate-status", false);
}
};
})();
</script>
The entire script is wrapped in an IIFE to avoid polluting the global scope. Functions that need to be called from onclick handlers are assigned to window.
2.3 API Helper Functions
Three helper functions handle the different request types:
The isBlob parameter on queryWorker is key — text-to-image returns binary image data, while other tasks return JSON.
2.4 The Six Demos
Demo 1: Text-to-Image
Uses Stable Diffusion XL to generate images from text prompts.
The response is a raw image blob — we use URL.createObjectURL() to display it without base64 encoding overhead.
Demo 2: AI Chat
Uses Llama 3.2 via HF’s OpenAI-compatible chat endpoint with conversation history.
Conversation context is maintained client-side in chatHistory, sliced to the last 12 messages to stay within token limits.
Demo 3: Image Classification (Vision)
Supports file upload, drag-and-drop, clipboard paste, and URL input.
The double requestAnimationFrame trick ensures the browser paints the bars at width: 0% first, then the CSS transition animates them to their final width.
Demo 4: Sentiment Analysis
Uses DistilBERT fine-tuned on SST-2 to classify text as positive or negative.
Demo 5: Summarization
Uses BART-large-CNN to condense long text.
The parameters object (max_length, min_length) is passed through to the HF Inference API to control output length.
Demo 6: Translation (EN ↔ ZH)
Uses Helsinki-NLP’s OPUS-MT models for bidirectional English-Chinese translation.
Switching direction swaps the model, updates labels, and refreshes example chips — all handled in updateTranslateDirection().
2.5 UI Patterns Worth Noting
Tab switching — Uses data-tab / data-panel attributes with a simple class toggle:
Example chips — Clickable chips that pre-fill the input field, reducing friction for first-time users:
Loading states — A reusable setLoading() function that disables the button, shows a spinner, and saves/restores the original button text:
XSS prevention — All user-generated text inserted into HTML uses escapeHtml():
2.6 Dark Mode Support
The CSS uses CSS custom properties that adapt to the Jekyll Chirpy theme’s dark mode:
Each variable has a fallback value, so the page works standalone even without a theme.
Models Used
| Demo | Model | Task | Notes |
|---|---|---|---|
| Text to Image | stabilityai/stable-diffusion-xl-base-1.0 |
text-to-image | 10–30s generation time |
| AI Chat | meta-llama/Llama-3.2-1B-Instruct |
chat completion | 1B param, fast responses |
| Vision | google/vit-large-patch16-224 |
image-classification | Top-5 ImageNet labels |
| Sentiment | distilbert-base-uncased-finetuned-sst-2-english |
text-classification | Binary positive/negative |
| Summarize | facebook/bart-large-cnn |
summarization | Trained on CNN/DailyMail |
| Translate |
Helsinki-NLP/opus-mt-en-zh / opus-mt-zh-en
|
translation | EN ↔ ZH bidirectional |
All models run on HF’s free inference tier. Response times vary — text models return in 1–3 seconds, image generation takes 10–30 seconds.
Try It Out
Check out the live AI Playground to see all 6 demos in action. The full source code for both the Cloudflare Worker and the frontend page is included in this post — fork it and build your own!
