-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
418 lines (388 loc) · 18.4 KB
/
index.html
File metadata and controls
418 lines (388 loc) · 18.4 KB
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
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>一束光,一句话: 安慰经文助手</title>
<style>
body {
font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Noto Sans", "PingFang SC", "Hiragino Sans GB", "Microsoft Yahei", sans-serif;
margin: 2rem auto;
max-width: 760px;
padding: 0 1rem;
background-image: url('background.png');
background-size: cover;
background-position: center;
background-attachment: fixed;
background-repeat: no-repeat;
}
h1 { margin-bottom: .25rem; text-shadow: 0 1px 2px rgba(255,255,255,0.7); }
.card { border: 1px solid #e5e7eb; border-radius: 12px; padding: 16px; margin: 16px 0; box-shadow: 0 1px 2px rgba(0,0,0,.04); background-color: rgba(255, 255, 255, 0.9); }
label { display:block; font-weight:600; margin:.5rem 0 .25rem; }
input, textarea, select { width: 100%; padding: .6rem .75rem; border: 1px solid #e5e7eb; border-radius: 10px; outline: none; box-sizing: border-box; }
button { cursor:pointer; padding: .7rem 1rem; border-radius: 999px; border: 0; background:#111827; color:#fff; font-weight:600; }
button[disabled] { opacity:.6; cursor:not-allowed; }
.row { display:flex; gap:.75rem; align-items:center; }
.checkbox-row { display:flex; align-items:center; gap:.5rem; margin-top:.75rem; }
.checkbox-row label { display:inline; font-weight:500; margin:0; }
.checkbox-row input[type="checkbox"] { width:auto; margin:0; }
.muted { color:#6b7280; font-size:.9rem; text-shadow: 0 1px 2px rgba(255,255,255,0.7); }
.passage { padding:.5rem .75rem; border-left:4px solid #11182710; background:#f9fafb; border-radius:8px; margin:.5rem 0; }
.error { color:#b91c1c; font-weight:600; background-color: rgba(255, 255, 255, 0.85); padding: .5rem; border-radius: 8px; }
pre { white-space:pre-wrap; word-break:break-word; }
.footer { color:#374151; font-size:.85rem; margin-top:2rem; text-shadow: 0 1px 2px rgba(255,255,255,0.7); }
</style>
</head>
<body>
<h1 id="header1"></h1>
<h2 id="header2"></h2>
<div class="muted" id="intro"></div>
<div class="card">
<div class="row">
<div style="flex-grow:1">
<label for="language" id="langLabel"></label>
<select id="language">
<option value="zh" selected>中文</option>
<option value="en">English</option>
</select>
</div>
<div>
<label for="max_passages" id="passagesLabel"></label>
<input type="number" id="max_passages" value="3" min="1" max="10" style="width: 60px;" />
</div>
</div>
<label for="sit" id="situationLabel"></label>
<textarea id="sit" rows="5"></textarea>
<label for="guide" id="guidanceLabel"></label>
<input id="guide" list="guideOptions" />
<datalist id="guideOptions"></datalist>
<div class="checkbox-row">
<input type="checkbox" id="enable_web_search" />
<label for="enable_web_search" id="webSearchLabel"></label>
</div>
<div class="row" style="margin-top:.75rem">
<button id="go"></button>
<span id="status" class="muted"></span>
</div>
</div>
<div id="result" class="card" style="display:none"></div>
<div id="err" class="error"></div>
<div class="footer" id="footer"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const API_BASE = "https://fastapi-helloworld-od7w.onrender.com";
const el = (id) => document.getElementById(id);
const btn = el('go');
const out = el('result');
const err = el('err');
const status = el('status');
const langSelect = el('language');
const ttsCache = { dev: null, pray: null };
const translations = {
zh: {
title: "一束光,一句话: 安慰经文助手",
header1: "一束光,一句话",
header2: "安慰经文助手",
intro: "输入你的处境,我们将给出相应经文参考、简短灵修与祷告。",
langLabel: "语言",
passagesLabel: "经文数",
situationLabel: "处境描述",
situationPlaceholder: "写下你正在经历的事,比如:项目延期、担心裁员、需要照顾孩子…",
guidanceLabel: "额外引导 (可选)",
guidancePlaceholder: "可选择常用引导,或直接输入你自己的要求",
guidanceOptions: [
{ value: "", label: "请选择常用引导(可留空)" },
{ value: "请列举一位与当前处境最相似的圣经正面人物,并详细说明他或她有哪些相似经历,以及神如何带领他或她。", label: "最相似的圣经人物与经历" },
{ value: "请多引用诗篇中关于安慰、盼望与信靠神的经文。", label: "多引用诗篇中的安慰经文" },
{ value: "请给出可以立刻实行的属灵回应与祷告方向。", label: "加入可立即实行的属灵回应" }
],
webSearchLabel: "启用网页搜索上下文",
buttonText: "获取安慰",
statusGenerating: "生成中,请稍候 (约10秒)...",
statusGeneratingWithSearch: "生成中,请稍候 (约40秒)...",
errorSituation: "请先填写处境描述。",
errorRequestFailed: "请求失败:",
footer: "前端托管在 GitHub Pages · 后端由 FastAPI (Render) 提供。为避免版权与版本差异,页面仅给出经文出处与极短摘句,请以你常用的译本核对上下文。",
passagesTitle: "推荐经文",
devotionalTitle: "灵修解读",
prayerTitle: "祷告",
philosophyLinkText: "前往哲学页面"
},
en: {
title: "Comfort Scriptures: A Ray of Light, A Word of Grace",
header1: "A Ray of Light, A Word of Grace",
header2: "Comfort Scriptures Assistant",
intro: "Describe your situation, and we will provide relevant scripture references, a short devotional, and a prayer.",
langLabel: "Language",
passagesLabel: "Passages",
situationLabel: "Describe your situation",
situationPlaceholder: "Write down what you are going through, e.g., project delays, fear of layoffs, taking care of children...",
guidanceLabel: "Optional Guidance",
guidancePlaceholder: "Choose a common guidance or type your own request",
guidanceOptions: [
{ value: "", label: "Select a common guidance (optional)" },
{ value: "Identify one Bible figure whose hopeful experience most closely matches the situation, and explain in detail how their journey parallels mine and how God guided them.", label: "Closest Bible figure and parallel journey" },
{ value: "Please include more passages from Psalms about comfort, hope, and trusting God.", label: "Include more comforting Psalms" },
{ value: "Please add practical spiritual responses and prayer directions I can follow right away.", label: "Add practical spiritual next steps" }
],
webSearchLabel: "Enable web search context",
buttonText: "Get Comfort",
statusGenerating: "Generating... this may take about 10 seconds.",
statusGeneratingWithSearch: "Generating... this may take about 40 seconds.",
errorSituation: "Please describe your situation first.",
errorRequestFailed: "Request failed: ",
footer: "Frontend hosted on GitHub Pages · Backend powered by FastAPI (Render). To avoid copyright and version differences, this page only provides scripture references and very short quotes. Please check the context in your preferred translation.",
passagesTitle: "Recommended Passages",
devotionalTitle: "Devotional",
prayerTitle: "Prayer",
philosophyLinkText: "Go to Philosophy Page"
}
};
function updateGuidanceOptions(lang) {
const t = translations[lang];
const guide = el('guide');
const guideOptions = el('guideOptions');
const currentValue = guide.value;
guide.placeholder = t.guidancePlaceholder;
guideOptions.innerHTML = '';
t.guidanceOptions
.filter((option) => option.value)
.forEach((option) => {
const node = document.createElement('option');
node.value = option.value;
node.label = option.label;
guideOptions.appendChild(node);
});
guide.value = currentValue;
}
function updateUI(lang) {
const t = translations[lang];
document.title = t.title;
el('header1').textContent = t.header1;
el('header2').textContent = t.header2;
el('intro').textContent = t.intro;
el('langLabel').textContent = t.langLabel;
el('passagesLabel').textContent = t.passagesLabel;
el('situationLabel').textContent = t.situationLabel;
el('sit').placeholder = t.situationPlaceholder;
el('guidanceLabel').textContent = t.guidanceLabel;
updateGuidanceOptions(lang);
el('webSearchLabel').textContent = t.webSearchLabel;
btn.textContent = t.buttonText;
el('footer').innerHTML = `${t.footer} · <a href=\"philosophy.html\">${t.philosophyLinkText}</a>`;
document.documentElement.lang = lang.startsWith('zh') ? 'zh-CN' : 'en';
}
async function fetchComfort() {
const lang = langSelect.value;
const t = translations[lang];
err.textContent = "";
out.style.display = 'none';
out.innerHTML = '';
const body = {
language: lang,
situation: el('sit').value.trim(),
guidance: el('guide').value.trim(),
max_passages: parseInt(el('max_passages').value, 10) || 3,
enable_web_search: el('enable_web_search').checked
};
if (!body.situation) {
err.textContent = t.errorSituation;
return;
}
btn.disabled = true;
status.textContent = body.enable_web_search ? t.statusGeneratingWithSearch : t.statusGenerating;
try {
const res = await fetch(`${API_BASE}/bible-comfort`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) {
const text = await res.text();
throw new Error(`HTTP ${res.status}: ${text}`);
}
const data = await res.json();
renderResult(data, lang);
} catch (e) {
console.error(e);
err.textContent = t.errorRequestFailed + (e.message || e);
console.log('Fetch failed detail =>', e);
} finally {
btn.disabled = false;
status.textContent = '';
}
}
function renderResult(data, lang) {
const t = translations[lang];
const passages = data.passages || [];
const devotional = data.devotional || '';
const prayer = data.prayer || '';
const disclaimer = data.disclaimer || '';
const h = [];
if (passages.length) {
h.push(`<h2>${t.passagesTitle}</h2>`);
passages.forEach(p => {
const quote = p.short_quote ? ` · <em>${escapeHtml(p.short_quote)}</em>` : '';
const reason = p.reason ? `<div class="muted">${escapeHtml(p.reason)}</div>` : '';
const full_text = p.full_passage_text ? `<pre style="margin-top: .5rem;">${escapeHtml(p.full_passage_text)}</pre>` : '';
h.push(`<div class="passage"><strong>${escapeHtml(p.ref)}</strong>${quote}${reason}${full_text}</div>`);
});
}
if (devotional) {
h.push(`<h2>${t.devotionalTitle}</h2>`);
h.push(`<pre id="devotionalText">${escapeHtml(devotional)}</pre>`);
h.push(`<div class="row" style="margin-top:.5rem">`
+ `<button id=\"playDev\">${lang.startsWith('zh') ? '播放灵修' : 'Play Devotional'}</button>`
+ `<audio id=\"audioDev\" controls style=\"display:none\"></audio>`
+ `<a id=\"downloadDev\" style=\"display:none; margin-left:.5rem\" download=\"devotional.mp3\">${lang.startsWith('zh') ? '下载 MP3' : 'Download MP3'}</a>`
+ `</div>`);
}
if (prayer) {
h.push(`<h2>${t.prayerTitle}</h2>`);
h.push(`<pre id="prayerText">${escapeHtml(prayer)}</pre>`);
h.push(`<div class="row" style="margin-top:.5rem">`
+ `<button id=\"playPrayer\">${lang.startsWith('zh') ? '播放祷告' : 'Play Prayer'}</button>`
+ `<audio id=\"audioPrayer\" controls style=\"display:none\"></audio>`
+ `<a id=\"downloadPrayer\" style=\"display:none; margin-left:.5rem\" download=\"prayer.mp3\">${lang.startsWith('zh') ? '下载 MP3' : 'Download MP3'}</a>`
+ `</div>`);
}
if (disclaimer) {
h.push(`<div class="muted">${escapeHtml(disclaimer)}</div>`);
}
out.innerHTML = h.join('\n');
out.style.display = 'block';
// Attach TTS handlers
const playDev = document.getElementById('playDev');
const playPrayer = document.getElementById('playPrayer');
if (playDev) {
playDev.addEventListener('click', async () => {
const text = (document.getElementById('devotionalText')?.textContent || '').trim();
if (ttsCache.dev) {
const audio = document.getElementById('audioDev');
const link = document.getElementById('downloadDev');
audio.src = ttsCache.dev;
audio.style.display = 'block';
if (link) { link.href = ttsCache.dev; link.style.display = 'inline-block'; }
try { await audio.play(); } catch (_) {}
} else {
await synthesizeAndPlay(text, lang, 'audioDev', 'downloadDev', playDev);
}
});
}
if (playPrayer) {
playPrayer.addEventListener('click', async () => {
const text = (document.getElementById('prayerText')?.textContent || '').trim();
if (ttsCache.pray) {
const audio = document.getElementById('audioPrayer');
const link = document.getElementById('downloadPrayer');
audio.src = ttsCache.pray;
audio.style.display = 'block';
if (link) { link.href = ttsCache.pray; link.style.display = 'inline-block'; }
try { await audio.play(); } catch (_) {}
} else {
await synthesizeAndPlay(text, lang, 'audioPrayer', 'downloadPrayer', playPrayer);
}
});
}
// Pre-generate audio in background to save time
if (devotional) {
const text = (document.getElementById('devotionalText')?.textContent || '').trim();
synthesizeToCache(text, lang, 'audioDev', 'downloadDev', 'dev');
}
if (prayer) {
const text = (document.getElementById('prayerText')?.textContent || '').trim();
synthesizeToCache(text, lang, 'audioPrayer', 'downloadPrayer', 'pray');
}
}
function escapeHtml(str){
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return String(str).replace(/[&<"']/g, s => map[s]);
}
btn.addEventListener('click', fetchComfort);
langSelect.addEventListener('change', (e) => {
const v = e.target.value;
try { localStorage.setItem('preferredLang', v); } catch (_) {}
updateUI(v);
});
// Detect default language from last saved value or browser setting
function detectDefaultLanguage() {
try {
const saved = localStorage.getItem('preferredLang');
if (saved === 'zh' || saved === 'en') return saved;
} catch (_) {}
const nav = navigator;
const candidates = [];
if (nav.languages && Array.isArray(nav.languages)) candidates.push(...nav.languages);
if (nav.language) candidates.push(nav.language);
const found = (candidates.find(l => String(l).toLowerCase().startsWith('zh')) ? 'zh' : 'en');
return found;
}
// Initial UI setup with detected default
const defaultLang = detectDefaultLanguage();
langSelect.value = defaultLang;
updateUI(defaultLang);
async function synthesizeAndPlay(text, lang, audioId, linkId, buttonEl) {
if (!text) return;
try {
if (buttonEl) buttonEl.disabled = true;
const res = await fetch(`${API_BASE}/tts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, language: lang, format: 'mp3' })
});
if (!res.ok) {
const msg = await res.text();
throw new Error(`HTTP ${res.status}: ${msg}`);
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const audio = document.getElementById(audioId);
const link = document.getElementById(linkId);
if (audio) {
audio.src = url;
audio.style.display = 'block';
try { await audio.play(); } catch (_) {}
}
if (link) {
link.href = url;
link.style.display = 'inline-block';
}
} catch (e) {
console.error('TTS error', e);
const prefix = lang.startsWith('zh') ? '语音合成失败:' : 'TTS failed: ';
err.textContent = prefix + (e.message || e);
} finally {
if (buttonEl) buttonEl.disabled = false;
}
}
async function synthesizeToCache(text, lang, audioId, linkId, cacheKey) {
if (!text) return;
try {
const res = await fetch(`${API_BASE}/tts`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, language: lang, format: 'mp3' })
});
if (!res.ok) return;
const blob = await res.blob();
const url = URL.createObjectURL(blob);
ttsCache[cacheKey] = url;
// Pre-bind sources but do not reveal controls yet
const audio = document.getElementById(audioId);
const link = document.getElementById(linkId);
if (audio) { audio.src = url; }
if (link) { link.href = url; }
} catch (_) {
// ignore background errors
}
}
});
</script>
</body>
</html>