XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

Add ElevenLabs anonymous TTS provider

- nodriver browser with hcaptcha accessibility cookie (browser_cookie3 auto-detection from logged-in browser, or hc_accessibility kwarg) - Single page.evaluate: invisible hcaptcha token + fetch + NDJSON/SSE audio_base64 chunk collection - Yields AudioResponse with /media/ path, following gTTS/EdgeTTS conventions (audio dict for voice/model/format/language overrides) - Registered in Provider lazy loader and audio package

3db6b830
Vini Louz <vinilouz@gmail.com>
提交于

代码差异

3 个文件 +190 -0
Modified g4f/Provider/__init__.py +3 -0
@@ -54,6 +54,8 @@ def _resolve_provider(name: str) -> ProviderType:
54 54 from g4f.Provider.needs_auth.DeepSeek import DeepSeek; return DeepSeek
55 55 elif name == "EdgeTTS":
56 56 from g4f.Provider.audio.EdgeTTS import EdgeTTS; return EdgeTTS
57 elif name == "ElevenLabs":
58 from g4f.Provider.audio.ElevenLabs import ElevenLabs; return ElevenLabs
57 59 elif name == "FenayAI":
58 60 from g4f.Provider.needs_auth.FenayAI import FenayAI; return FenayAI
59 61 elif name == "GLM":
@@ -200,6 +202,7 @@ _provider_names = [
200 202 "DeepInfra",
201 203 "DeepSeek",
202 204 "EdgeTTS",
205 "ElevenLabs",
203 206 "FenayAI",
204 207 "GLM",
205 208 "Gemini",
Added g4f/Provider/audio/ElevenLabs.py +186 -0
@@ -0,0 +1,186 @@
1 from __future__ import annotations
2
3 import os
4 import json
5 import base64
6
7 try:
8 import zendriver as nodriver
9 has_nodriver = True
10 except ImportError:
11 has_nodriver = False
12
13 from ...typing import AsyncResult, Messages
14 from ...providers.response import AudioResponse
15 from ...image.copy_images import get_filename, get_media_dir, ensure_media_dir
16 from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
17 from ..helper import get_last_message
18 from ...cookies import get_cookies
19 from ...requests import get_nodriver, get_cookie_params_from_dict
20
21
22 class ElevenLabs(AsyncGeneratorProvider, ProviderModelMixin):
23 """Anonymous ElevenLabs TTS via browser hcaptcha token.
24
25 Requires:
26 pip install "g4f[slim]" (zendriver; included in slim/all extras)
27 hcaptcha accessibility cookie — log in once at
28 https://dashboard.hcaptcha.com/signup?type=accessibility in your
29 browser (read automatically via browser_cookie3), or pass
30 hc_accessibility="..." kwarg. Cookie valid ~24h.
31
32 Usage:
33 client.chat.completions.create(
34 model="elevenlabs-tts",
35 messages=[{"role": "user", "content": "Olá"}],
36 audio={"voice": "tS45q0QcrDHqHoaWdCDR", "language": "pt"},
37 )
38 """
39
40 label = "ElevenLabs TTS"
41 url = "https://elevenlabs.io"
42 working = has_nodriver
43 use_nodriver = has_nodriver
44 needs_auth = True # hcaptcha accessibility cookie
45
46 model_id = "elevenlabs-tts"
47 default_model = "eleven_v3"
48 default_voice = "tS45q0QcrDHqHoaWdCDR"
49 default_format = "mp3_44100_128"
50 default_language = "pt"
51
52 @classmethod
53 async def create_async_generator(
54 cls,
55 model: str,
56 messages: Messages,
57 prompt: str = None,
58 audio: dict = {},
59 proxy: str = None,
60 **kwargs
61 ) -> AsyncResult:
62 prompt = get_last_message(messages, prompt)
63 if not prompt:
64 raise ValueError("Prompt is empty.")
65
66 voice = audio.get("voice", cls.default_voice)
67 model_id = audio.get("model", cls.default_model)
68 output_format = audio.get("format", cls.default_format)
69 language = audio.get("language", cls.default_language)
70
71 # hcaptcha accessibility cookie — kwarg, then browser cookie store
72 cookie_val = kwargs.get("hc_accessibility")
73 if not cookie_val:
74 cookie_val = get_cookies(".hcaptcha.com", raise_requirements_error=False).get("hc_accessibility")
75 if not cookie_val:
76 raise RuntimeError(
77 "hCaptcha accessibility cookie required: log in at "
78 "https://dashboard.hcaptcha.com/signup?type=accessibility "
79 "in your browser, or pass hc_accessibility=\"...\"."
80 )
81
82 browser, stop_browser = await get_nodriver(proxy=proxy)
83 try:
84 cookie_params = get_cookie_params_from_dict(
85 {"hc_accessibility": cookie_val},
86 domain=".hcaptcha.com"
87 )
88 await browser.cookies.set_all(cookie_params)
89
90 page = await browser.get(cls.url)
91 # Wait until DOM body exists before injecting elements
92 await page.evaluate("""
93 document.body || new Promise(r => {
94 document.addEventListener('DOMContentLoaded', r, {once: true});
95 })
96 """, await_promise=True)
97
98 chunks = await page.evaluate(
99 _build_js(prompt, voice, model_id, output_format, language),
100 await_promise=True
101 )
102 finally:
103 await stop_browser()
104
105 if not chunks:
106 raise RuntimeError("No audio chunks received from ElevenLabs.")
107
108 audio_bytes = b"".join(base64.b64decode(c) for c in chunks)
109 # ponytail: whole response buffered; streaming per-chunk yield if memory matters
110 filename = get_filename([cls.__name__], prompt, ".mp3", prompt)
111 target_path = os.path.join(get_media_dir(), filename)
112 ensure_media_dir()
113 with open(target_path, "wb") as f:
114 f.write(audio_bytes)
115
116 yield AudioResponse(f"/media/{filename}", text=prompt)
117
118
119 def _build_js(prompt: str, voice: str, model_id: str, output_format: str, language: str) -> str:
120 """Render invisible hcaptcha, fetch elevenlabs API with token, collect SSE audio chunks."""
121 _text = json.dumps(prompt)
122 _voice = json.dumps(voice)
123 _model = json.dumps(model_id)
124 _format = json.dumps(output_format)
125 _lang = json.dumps(language)
126
127 return f"""(async () => {{
128 const c = document.createElement('div');
129 c.id = 'hc-' + Math.random().toString(36).slice(2);
130 c.style.display = 'none';
131 document.body.appendChild(c);
132 if (typeof hcaptcha === 'undefined') {{
133 await new Promise((r, e) => {{
134 const s = document.createElement('script');
135 s.src = 'https://js.hcaptcha.com/1/api.js';
136 s.onload = r; s.onerror = e;
137 document.head.appendChild(s);
138 }});
139 await new Promise(r => setTimeout(r, 1500));
140 }}
141 const token = await new Promise((res, rej) => {{
142 const w = hcaptcha.render(c.id, {{
143 sitekey: '8e58fe8c-1a48-4f94-88ae-8e90b586a192',
144 size: 'invisible',
145 callback: (t) => res(t),
146 'error-callback': (e) => rej(new Error('hcaptcha: ' + e))
147 }});
148 hcaptcha.execute(w);
149 }});
150 const r = await fetch(
151 'https://api.elevenlabs.io/v1/text-to-speech/' + {_voice} + '/stream/with-timestamps/anonymous?output_format=' + {_format},
152 {{
153 method: 'POST',
154 headers: {{'Content-Type': 'application/json'}},
155 body: JSON.stringify({{
156 text: {_text},
157 model_id: {_model},
158 voice_settings: {{speed: 1}},
159 hcaptcha_token: token,
160 language_code: {_lang}
161 }})
162 }}
163 );
164 if (!r.ok) throw new Error(r.status + ' ' + await r.text());
165 const reader = r.body.getReader(), dec = new TextDecoder();
166 let buf = '', chunks = [];
167 while (true) {{
168 const {{done, value}} = await reader.read();
169 if (done) break;
170 buf += dec.decode(value, {{stream: true}});
171 const lines = buf.split('\\n');
172 buf = lines.pop() || '';
173 for (const ln of lines) {{
174 const t = ln.trim();
175 if (!t) continue;
176 // Accept both plain NDJSON and SSE "data:" prefixed lines
177 const d = t.startsWith('data:') ? t.slice(5).trim() : t;
178 try {{
179 const p = JSON.parse(d);
180 if (p.audio_base64) chunks.push(p.audio_base64);
181 }} catch (e) {{}}
182 }}
183 }}
184 if (!chunks.length) throw new Error('No audio chunks');
185 return chunks;
186 }})()"""
Modified g4f/Provider/audio/__init__.py +1 -0
@@ -1,4 +1,5 @@
1 1 from .EdgeTTS import EdgeTTS
2 from .ElevenLabs import ElevenLabs
2 3 from .gTTS import gTTS
3 4 from .MarkItDown import MarkItDown
4 5 from .OpenAIFM import OpenAIFM