-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphilosophy.html
More file actions
375 lines (348 loc) · 15.4 KB
/
philosophy.html
File metadata and controls
375 lines (348 loc) · 15.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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>The Consolations of Philosophy</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_philosophy.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>Chinese</option>
<option value="en">English</option>
</select>
</div>
</div>
<label for="sit" id="situationLabel"></label>
<textarea id="sit" rows="5"></textarea>
<label for="guide" id="guidanceLabel"></label>
<input id="guide" />
<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 = { refl: null, ex: null };
const translations = {
zh: {
title: "哲学的慰藉",
header1: "哲学的慰藉",
header2: "温柔反思与轻练习",
intro: "请输入你的处境,我们将提供温柔、体贴的哲学反思与轻柔可行的练习。",
langLabel: "语言",
situationLabel: "处境描述",
situationPlaceholder: "写下你正在经历的事,例如:项目延期、担心裁员、照顾孩子压力……",
guidanceLabel: "额外引导(可选)",
guidancePlaceholder: "例如:关注幸福哲学, 语气更温柔、更少说教;先共情再建议;给 2-5 分钟的小练习",
webSearchLabel: "启用网页搜索上下文",
buttonText: "获取慰藉",
statusGenerating: "生成中,请稍候(约 10 秒)...",
statusGeneratingWithSearch: "生成中,请稍候(约 40 秒)...",
errorSituation: "请先填写处境描述。",
errorRequestFailed: "请求失败:",
footer: "前端托管在 GitHub Pages,后端由 FastAPI(Render)提供。",
reflectionTitle: "哲学反思",
exerciseTitle: "练习步骤",
playReflection: "播放反思",
playExercise: "播放练习",
downloadMp3: "下载 MP3",
ttsFailedPrefix: "语音合成失败:",
indexLinkText: "前往经文页面"
},
en: {
title: "The Consolations of Philosophy",
header1: "The Consolations of Philosophy",
header2: "Gentle Reflections and Practices",
intro: "Describe your situation; we will provide a warm, gentle philosophical reflection and a soft, easy-to-try exercise.",
langLabel: "Language",
situationLabel: "Describe your situation",
situationPlaceholder: "Write what you are going through, e.g., project delays, fear of layoffs, caregiving stress...",
guidanceLabel: "Additional guidance (optional)",
guidancePlaceholder: "e.g., focus on well being philosophy, softer tone, less didactic; start with empathy; 2–5 minute practice",
webSearchLabel: "Enable web search context",
buttonText: "Get Consolation",
statusGenerating: "Generating, please wait (~10s)...",
statusGeneratingWithSearch: "Generating, please wait (~40s)...",
errorSituation: "Please enter your situation first.",
errorRequestFailed: "Request failed: ",
footer: "Frontend on GitHub Pages - Backend by FastAPI (Render).",
reflectionTitle: "Reflection",
exerciseTitle: "Exercise",
playReflection: "Play Reflection",
playExercise: "Play Exercise",
downloadMp3: "Download MP3",
ttsFailedPrefix: "TTS failed: ",
indexLinkText: "Go to Scriptures Page"
}
};
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('situationLabel').textContent = t.situationLabel;
el('sit').placeholder = t.situationPlaceholder;
el('guidanceLabel').textContent = t.guidanceLabel;
el('guide').placeholder = t.guidancePlaceholder;
el('webSearchLabel').textContent = t.webSearchLabel;
btn.textContent = t.buttonText;
el('footer').innerHTML = `${t.footer} · <a href=\"index.html\">${t.indexLinkText}</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(),
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}/philosophy-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 reflection = data.reflection || '';
const exercise = data.exercise || '';
const disclaimer = data.disclaimer || '';
const h = [];
// Passages rendering omitted by design.
if (reflection) {
h.push(`<h2>${t.reflectionTitle}</h2>`);
h.push(`<pre id="reflectionText">${escapeHtml(reflection)}</pre>`);
h.push(`<div class="row" style="margin-top:.5rem">`
+ `<button id=\"playRefl\">${t.playReflection}</button>`
+ `<audio id=\"audioRefl\" controls style=\"display:none\"></audio>`
+ `<a id=\"downloadRefl\" style=\"display:none; margin-left:.5rem\" download=\"reflection.mp3\">${t.downloadMp3}</a>`
+ `</div>`);
}
if (exercise) {
h.push(`<h2>${t.exerciseTitle}</h2>`);
h.push(`<pre id="exerciseText">${escapeHtml(exercise)}</pre>`);
h.push(`<div class="row" style="margin-top:.5rem">`
+ `<button id=\"playEx\">${t.playExercise}</button>`
+ `<audio id=\"audioEx\" controls style=\"display:none\"></audio>`
+ `<a id=\"downloadEx\" style=\"display:none; margin-left:.5rem\" download=\"exercise.mp3\">${t.downloadMp3}</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 playRefl = document.getElementById('playRefl');
const playEx = document.getElementById('playEx');
if (playRefl) {
playRefl.addEventListener('click', async () => {
const text = (document.getElementById('reflectionText')?.textContent || '').trim();
if (ttsCache.refl) {
const audio = document.getElementById('audioRefl');
const link = document.getElementById('downloadRefl');
audio.src = ttsCache.refl;
audio.style.display = 'block';
if (link) { link.href = ttsCache.refl; link.style.display = 'inline-block'; }
try { await audio.play(); } catch (_) {}
} else {
await synthesizeAndPlay(text, lang, 'audioRefl', 'downloadRefl', playRefl);
}
});
}
if (playEx) {
playEx.addEventListener('click', async () => {
const text = (document.getElementById('exerciseText')?.textContent || '').trim();
if (ttsCache.ex) {
const audio = document.getElementById('audioEx');
const link = document.getElementById('downloadEx');
audio.src = ttsCache.ex;
audio.style.display = 'block';
if (link) { link.href = ttsCache.ex; link.style.display = 'inline-block'; }
try { await audio.play(); } catch (_) {}
} else {
await synthesizeAndPlay(text, lang, 'audioEx', 'downloadEx', playEx);
}
});
}
// Pre-generate audio in background to save time
if (reflection) {
const text = (document.getElementById('reflectionText')?.textContent || '').trim();
synthesizeToCache(text, lang, 'audioRefl', 'downloadRefl', 'refl');
}
if (exercise) {
const text = (document.getElementById('exerciseText')?.textContent || '').trim();
synthesizeToCache(text, lang, 'audioEx', 'downloadEx', 'ex');
}
}
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 lang = langSelect.value;
const t = translations[lang];
err.textContent = (t.ttsFailedPrefix || 'TTS failed: ') + (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>