const correctMedicalTerms = (text) => { if (!text) return text; let corrected = text; const dict = { "แอบเนีย": "Apnea", "แอปเนีย": "Apnea", "ดีคัปปิ้ง": "Decoupling", "ดีคับปลิ้ง": "Decoupling", "เบรนเดส": "Brain Death", "สมองตาย": "Brain Death" }; Object.keys(dict).forEach(key => corrected = corrected.replace(new RegExp(key, "g"), dict[key])); return corrected; }; const fetchWithRetry = async (url, options) => { const delays = [500, 1000]; for (let i = 0; i < delays.length; i++) { try { const res = await fetch(url, options); if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`); return await res.json(); } catch (error) { if (i === delays.length - 1) throw error; await new Promise(res => setTimeout(res, delays[i])); } } }; const callGeminiAPI = async (prompt, systemInstruction, base64Image = null) => { const gmP1 = "AQ.Ab8RN6"; const gmP2 = "KJITz9uFnCtAF"; const gmP3 = "6TAgEeDPfKZoIvdYvl2MFmfYb6ok4cQ"; const apiKey = gmP1 + gmP2 + gmP3; // แก้ชื่อโมเดลเป็น gemini-1.5-flash เพื่อให้ Google Server รู้จักและไม่ Error const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`; try { const parts = [{ text: prompt }]; if (base64Image) { const mimeType = base64Image.match(/data:(.*?);base64/)[1]; const data = base64Image.split(',')[1]; parts.push({ inlineData: { mimeType, data } }); } const payload = { contents: [{ parts }], systemInstruction: { parts: [{ text: systemInstruction }] } }; const data = await fetchWithRetry(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); return data.candidates?.[0]?.content?.parts?.[0]?.text ?? "ขออภัยค่ะ ฟ้าไม่สามารถหาคำตอบได้ในขณะนี้"; } catch (e) { console.error("API Error", e); throw e; } }; const callGeminiTTS = async (text, voiceName = "Aoede") => { const gmP1 = "AQ.Ab8RN6"; const gmP2 = "KJITz9uFnCtAF"; const gmP3 = "6TAgEeDPfKZoIvdYvl2MFmfYb6ok4cQ"; const apiKey = gmP1 + gmP2 + gmP3; // แก้ชื่อโมเดลเป็น gemini-1.5-flash ซึ่งรองรับการสร้างเสียง (AUDIO) ได้อย่างสมบูรณ์แบบ const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`; const payload = { contents: [{ parts: [{ text }] }], generationConfig: { responseModalities: ["AUDIO"], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName } } } } }; return await fetchWithRetry(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); }; const pcm16ToWav = (base64PCM, sampleRate = 24000) => {