-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
483 lines (474 loc) · 17.8 KB
/
index.html
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
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Ai PPT</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<!-- 大纲生成 -->
<div id="div1">
<div style="margin-bottom: 50px;">
<h1>🤖 AI智能生成PPT演示文稿</h1>
<div style="font-size: 14px;color: #999;">生成大纲 ---> 挑选模板 --> 实时生成PPT</div>
</div>
<label>主题:</label>
<input type="text" id="subject" placeholder="请输入PPT主题" />
<button onclick="generateOutline()">生成大纲</button>
<button id="nextTo2" class="next_but" onclick="nextTo2()">下一步:选择模板</button>
<div id="outline"></div>
</div>
<!-- 选择模板 -->
<div id="div2">
<div style="text-align: center;margin: 10px;">
<div>---- 选择模板 ----</div>
<button id="nextTo3" class="next_but" style="margin-top: 10px;" onclick="nextTo3()">下一步:生成PPT</button>
</div>
<div id="templates">模板加载中...</div>
</div>
<!-- PPT页面 -->
<div id="div3">
<div id="desc" style="text-align: center;margin-top: 20px">
<span id="desc_msg">正在生成中,请稍后...</span>
<span id="desc_time" style="margin-left: 5px"></span>
</div>
<div class="left_div">
<div class="left_div_child">
<div id="left_image_list" class="left_div_child_child">
<!--
<div class="left_div_item" onclick="drawPptx(0)">
<div class="left_div_item_index">1</div>
<img src="1.png" class="left_div_item_img" />
</div>
-->
</div>
</div>
</div>
<div class="right_div">
<a id="pptDownload" href="javascript:downloadPptx()">下载</a>
<div id="right_container" style="padding-top: 8px;">
<svg id="right_canvas"></svg>
</div>
</div>
</div>
<script src="static/sse.js"></script>
<script src="static/chart.js"></script>
<script src="static/geometry.js"></script>
<script src="static/ppt2svg.js"></script>
<script src="static/ppt2canvas.js"></script>
<script src="static/base64js.js"></script>
<script src="static/pako.js"></script>
<script src="static/marked.js"></script>
<script>
var pptxId = null
var outline = ''
var templateId = ''
var pptxObj = null
var selectIdx = 0
var mTimer = null
var markdownRenderer = new marked.Renderer()
marked.setOptions({
renderer: markdownRenderer,
async: false,
gfm: true,
tables: true,
breaks: false,
pedantic: false,
silent: true
})
// 文多多AiPPT
// 官网 https://docmee.cn
// 开放平台 https://docmee.cn/open-platform/api#接口鉴权
var apiKey = ''
var token = null
// 这里只是demo演示,创建token请在服务端调用
function createApiToken(apiKey, uid, limit) {
if (!apiKey) {
alert('请在代码中设置apiKey')
return
}
let url = 'https://docmee.cn/api/user/createApiToken'
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Api-Key', apiKey)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify({ uid, limit }))
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let resp = JSON.parse(xhr.responseText)
if (resp.code != 0) {
alert('创建token异常:' + resp.message)
return
}
token = resp.data.token
}
}
}
xhr.onerror = function (e) {
alert('创建token异常')
}
}
createApiToken(apiKey, 'test', null)
// svg
var painter = new Ppt2Svg('right_canvas')
var canvas = painter.svgNode()
painter.setMode('edit')
function generateOutline() {
outline = ''
let subject = document.getElementById('subject').value
if (!subject) {
alert('请输入主题')
return
}
if (subject.length < 3) {
alert('主题太短')
return
}
const url = 'https://docmee.cn/api/ppt/generateOutline'
var source = new SSE(url, {
method: 'POST',
headers: {
'token': token,
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
},
payload: JSON.stringify({ subject }),
})
source.onmessage = function (data) {
let json = JSON.parse(data.data)
if (json.status == -1) {
alert('生成大纲异常:' + json.error)
return
}
outline += json.text
document.getElementById('outline').innerHTML = window.marked.marked(outline.replaceAll('```markdown', '').replaceAll('```', ''))
window.scrollTo({ behavior: 'smooth', top: document.body.scrollHeight })
}
source.onend = function (data) {
if (data.data.startsWith('{') && data.data.endsWith('}')) {
const json = JSON.parse(data.data)
if (json.code != 0) {
alert('生成大纲异常:' + json.message)
return
}
}
document.getElementById('nextTo2').style.display = 'inline-block'
window.scrollTo(0, 0)
}
source.onerror = function (err) {
console.error('生成大纲异常', err)
alert('生成大纲异常')
}
source.stream()
}
function nextTo2() {
document.getElementById('nextTo2').style.display = 'none'
document.getElementById('div1').style.display = 'none'
document.getElementById('div2').style.display = 'block'
window.scrollTo(0, 0)
loadTemplates()
}
function loadTemplates() {
let url = 'https://docmee.cn/api/ppt/randomTemplates'
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('token', token)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify({ page: 1, size: 28, filters: { type: 1 } }))
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let resp = JSON.parse(xhr.responseText)
let list = resp.data
let templates = ''
for (let i = 0; i < list.length; i++) {
let id = list[i].id
// 图片需要拼接 token 访问
let coverUrl = list[i].coverUrl + '?token=' + token
let html = `<div id="${id}" class="template" onclick="selectTemplate('${id}')">`
html += `<img id="img_${id}" src="${coverUrl}" />`
html += '</div>'
templates += html
}
templates += '<div style="width: 100%;padding: 10px;text-align: center;"><button onclick="loadTemplates()">换一批</button></div>'
document.getElementById('templates').innerHTML = templates
selectTemplate(list[0].id)
}
}
}
xhr.onerror = function (e) {
console.error(e)
}
}
async function selectTemplate(id) {
if (templateId) {
let ele = document.getElementById(templateId)
if (ele) {
ele.classList.remove('item_select')
}
}
templateId = id
document.getElementById('nextTo3').style.display = 'inline-block'
document.getElementById(id).classList.add('item_select')
let color = await calcSubjectColor(document.getElementById(`img_${id}`).src)
document.body.style.background = color
}
function nextTo3() {
document.body.style.background = null
document.getElementById('nextTo3').style.display = 'none'
document.getElementById('div2').style.display = 'none'
document.getElementById('div3').style.display = 'block'
generatePptx()
}
function generatePptx() {
var count = 0
var timer = setInterval(() => {
count = count + 1
document.getElementById('desc').style.display = 'block'
document.getElementById('desc_time').innerHTML = count + '秒'
}, 1000)
const url = 'https://docmee.cn/api/ppt/generateContent'
var source = new SSE(url, {
method: 'POST',
headers: {
'token': token,
'Content-Type': 'application/json',
'Cache-Control': 'no-cache'
},
payload: JSON.stringify({ outlineMarkdown: outline, asyncGenPptx: true, templateId }),
})
source.onmessage = function (data) {
let json = JSON.parse(data.data)
if (json.status == -1) {
alert('生成PPT异常:' + json.error)
return
}
if (json.pptId) {
document.getElementById('desc_msg').innerText = `正在生成中,进度 ${json.current}/${json.total},请稍后...`
asyncGenPptxInfo(json.pptId)
}
}
source.onend = function (data) {
if (data.data.startsWith('{') && data.data.endsWith('}')) {
const json = JSON.parse(data.data)
if (json.code != 0) {
alert('生成PPT异常:' + json.message)
return
}
}
clearInterval(timer)
document.getElementById('desc').style.display = 'none'
document.getElementById('pptDownload').style.display = 'inline-block'
drawPptxList()
}
source.onerror = function (err) {
clearInterval(timer)
console.error('生成内容异常', err)
alert('生成内容异常')
}
source.stream()
}
function asyncGenPptxInfo(id) {
pptxId = id
let url = `https://docmee.cn/api/ppt/asyncPptInfo?pptId=${pptxId}`
let xhr = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.setRequestHeader('token', token)
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
let resp = JSON.parse(xhr.responseText)
let gzipBase64 = resp.data.pptxProperty
let gzip = base64js.toByteArray(gzipBase64)
let json = pako.ungzip(gzip, { to: 'string' })
pptxObj = JSON.parse(json)
drawPptxList(resp.data.current - 1, true)
}
}
}
xhr.onerror = function (e) {
console.error(e)
document.getElementById('desc').style.display = 'none'
}
}
async function drawPptxList(idx, asyncGen) {
if (idx == null || document.getElementById('img_' + idx) == null) {
let html = ''
for (let i = 0; i < pptxObj.pages.length; i++) {
if (asyncGen && i > idx) {
break
}
html += '<div class="left_div_item" onclick="drawPptx(' + i + ')">'
html += '<div class="left_div_item_index">' + (i + 1) + '</div>'
html += '<canvas id="img_' + i + '" width="288" height="162" style="width: 144px;height: 81px;" class="left_div_item_img" />'
html += '</div>'
}
if (asyncGen && idx < pptxObj.pages.length - 1) {
html += '<div class="left_div_item">'
html += '<div class="left_div_item_index">' + (idx + 2) + '</div>'
html += '<div style="width: 144px;height: 81px;text-align: center;line-height: 81px;color: #666;cursor: default;" class="left_div_item_img">生成中...</div>'
html += '</div>'
}
let itemList = document.getElementById('left_image_list')
itemList.innerHTML = html
if (asyncGen) {
itemList.scrollBy(0, itemList.scrollHeight)
}
for (let i = 0; i < pptxObj.pages.length; i++) {
let imgCanvas = document.getElementById('img_' + i)
if (!imgCanvas) {
continue
}
try {
let _ppt2Canvas = new Ppt2Canvas(imgCanvas)
await _ppt2Canvas.drawPptx(pptxObj, i)
} catch(e) {
console.log('渲染第' + (i + 1) + '页封面异常', e)
}
}
} else if (idx != null) {
try {
let imgCanvas = document.getElementById('img_' + idx)
let _ppt2Canvas = new Ppt2Canvas(imgCanvas)
await _ppt2Canvas.drawPptx(pptxObj, idx)
} catch(e) {
console.log('渲染第' + (idx + 1) + '页封面异常', e)
}
}
drawPptx(idx || 0)
}
function drawPptx(idx) {
if (idx == 0) {
document.getElementById('img_0').scrollIntoView(true)
}
let lastSelect = document.getElementById('img_' + selectIdx)
lastSelect && lastSelect.classList.remove('item_select')
document.getElementById('right_canvas').style.display = 'block'
selectIdx = idx
let current = document.getElementById('img_' + idx)
current.classList.add('item_select')
painter.drawPptx(pptxObj, idx)
}
function downloadPptx() {
let download = document.getElementById('pptDownload')
download.innerText = '正在下载中...'
let xhr = new XMLHttpRequest()
xhr.open('POST', 'https://docmee.cn/api/ppt/downloadPptx')
xhr.setRequestHeader('token', token)
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.onload = function() {
if (this.status == 200) {
download.innerText = '下载'
let resp = JSON.parse(this.responseText)
let fileUrl = resp.data.fileUrl
let a = document.createElement('a')
a.href = fileUrl
a.download = (resp.data.subject || 'download') + '.pptx'
a.click()
}
}
xhr.onerror = function (e) {
console.error(e)
download.innerText = '下载'
}
xhr.send(JSON.stringify({ id: pptxId }))
}
function loadPptx(id) {
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://docmee.cn/api/ppt/loadPptx?id=' + id)
xhr.setRequestHeader('token', token)
xhr.onload = function() {
if (this.status == 200) {
let resp = JSON.parse(this.responseText)
let pptInfo = resp.data.pptInfo
let gzipBase64 = pptInfo.pptxProperty
let gzip = base64js.toByteArray(gzipBase64)
let json = pako.ungzip(gzip, { to: 'string' })
pptxObj = JSON.parse(json)
drawPptxList(0, false)
}
}
xhr.onerror = function (e) {
console.error(e)
}
xhr.send()
}
async function calcSubjectColor(src) {
let img = new Image()
await new Promise(resolve => {
let eqOrigin = src.startsWith('data:') || src.startsWith(document.location.origin) || (src.startsWith('//') && (document.location.protocol + src).startsWith(document.location.origin))
if (!eqOrigin) {
img.crossOrigin = 'anonymous'
}
img.src = src
img.onload = function() {
resolve(img)
}
img.onerror = function (e) {
resolve()
}
})
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
canvas.width = img.width
canvas.height = img.height
ctx.drawImage(img, 0, 0)
let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
let data = imageData.data
let map = {}
for (let i = 0; i < data.length; i += 4) {
let r = data[i]
let g = data[i + 1]
let b = data[i + 2]
let rgb = r + g + b
if (rgb <= 50 || rgb >= 660) {
// 忽略黑白
continue
}
let color = `${r},${g},${b}`
map[color] = (map[color] || 0) + 1
}
let valueMap = {}
for (let k in map) {
let v = map[k]
let ks = valueMap[v]
if (ks) {
ks.push(k)
} else {
valueMap[v] = [k]
}
}
let colors = []
let values = Object.values(map).sort()
for (let i = values.length - 1; i >= 0; i--) {
let ks = valueMap[values[i]]
for (let j = 0; j < ks.length; j++) {
colors.push(ks[j])
if (colors.length >= 3) {
break
}
}
if (colors.length >= 3) {
break
}
}
// return `rgb(${colors[0]})`
return `linear-gradient(to bottom right, rgb(${colors[0]}), rgb(${colors[1]}), rgb(${colors[2]}))`
}
function resetSize() {
let width = Math.max(Math.min(document.body.clientWidth - 400, 1600), 480)
painter.resetSize(width, width * 0.5625)
}
window.addEventListener('resize', function() {
mTimer && clearTimeout(mTimer)
mTimer = setTimeout(() => {
resetSize()
}, 50)
})
document.getElementById('div1').style.display = 'block'
resetSize()
</script>
</body>
</html>