-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathapp.py
More file actions
2398 lines (2049 loc) · 81.9 KB
/
app.py
File metadata and controls
2398 lines (2049 loc) · 81.9 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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
# Suppress SyntaxWarnings from third-party packages (e.g., pydub regex patterns)
warnings.filterwarnings("ignore", category=SyntaxWarning)
from fastapi import (
FastAPI,
Depends,
HTTPException,
Header,
Request,
Form,
UploadFile,
File,
WebSocket,
WebSocketDisconnect,
)
from fastapi.responses import StreamingResponse, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import Any, List, Dict, Union, Optional
import struct
from Pipes import Pipes
from RequestQueue import RequestQueue
import base64
import os
import logging
import re
import uuid
import time
import asyncio
from Globals import getenv
DEFAULT_MODEL = getenv("DEFAULT_MODEL")
WHISPER_MODEL = getenv("WHISPER_MODEL")
logging.basicConfig(
level=getenv("LOG_LEVEL"),
format=getenv("LOG_FORMAT"),
force=True,
)
# SRT/VTT timestamp formatting helpers
def format_timestamp_srt(seconds: float) -> str:
"""Convert seconds to SRT timestamp format: HH:MM:SS,mmm"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds - int(seconds)) * 1000)
return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
def format_timestamp_vtt(seconds: float) -> str:
"""Convert seconds to VTT timestamp format: HH:MM:SS.mmm"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds - int(seconds)) * 1000)
return f"{hours:02d}:{minutes:02d}:{secs:02d}.{millis:03d}"
def segments_to_srt(segments: list) -> str:
"""Convert segments to SRT format, including speaker labels if present."""
srt_lines = []
for i, seg in enumerate(segments, 1):
start = format_timestamp_srt(seg["start"])
end = format_timestamp_srt(seg["end"])
srt_lines.append(f"{i}")
srt_lines.append(f"{start} --> {end}")
text = seg["text"]
if "speaker" in seg:
text = f"[{seg['speaker']}]: {text}"
srt_lines.append(text)
srt_lines.append("")
return "\n".join(srt_lines)
def segments_to_vtt(segments: list) -> str:
"""Convert segments to WebVTT format, including speaker labels if present."""
vtt_lines = ["WEBVTT", ""]
for seg in segments:
start = format_timestamp_vtt(seg["start"])
end = format_timestamp_vtt(seg["end"])
vtt_lines.append(f"{start} --> {end}")
text = seg["text"]
if "speaker" in seg:
text = f"<v {seg['speaker']}>{text}</v>"
vtt_lines.append(text)
vtt_lines.append("")
return "\n".join(vtt_lines)
# Initialize request queue — initial value; updated after Pipes init to match n_parallel
MAX_CONCURRENT_REQUESTS = int(getenv("MAX_CONCURRENT_REQUESTS", "5"))
MAX_QUEUE_SIZE = int(getenv("MAX_QUEUE_SIZE", "100"))
request_queue = RequestQueue(
max_concurrent_requests=MAX_CONCURRENT_REQUESTS, max_queue_size=MAX_QUEUE_SIZE
)
pipe = Pipes()
# Align queue concurrency with the LLM's actual n_parallel.
# The LLM can handle n_parallel requests simultaneously via continuous batching,
# so the queue should allow at least that many through.
if pipe.llm and hasattr(pipe.llm, "n_parallel") and pipe.llm.n_parallel > 1:
effective_concurrent = max(MAX_CONCURRENT_REQUESTS, pipe.llm.n_parallel)
if effective_concurrent != request_queue.max_concurrent_requests:
request_queue.max_concurrent_requests = effective_concurrent
logging.info(
f"[Queue] Aligned max_concurrent_requests={effective_concurrent} "
f"with LLM n_parallel={pipe.llm.n_parallel}"
)
app = FastAPI(title="ezlocalai Server", docs_url="/")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Queue management
@app.on_event("startup")
async def startup_event():
await request_queue.start()
# Initialize wake word manager in voice server mode
from Pipes import is_voice_server_mode
if is_voice_server_mode():
logging.info(
"[WakeWord] Voice server mode detected, initializing wake word manager"
)
try:
from ezlocalai.WakeWord import WakeWordManager, set_wakeword_manager
from pathlib import Path
# In voice server mode, we can optionally share Chatterbox TTS with wake word training
# This allows voice cloning for wake word samples
chatterbox_model = None
try:
# Pre-load TTS to get the Chatterbox model for wake word training
tts = pipe._get_tts()
if hasattr(tts, "model"):
chatterbox_model = tts.model
logging.info(
"[WakeWord] Chatterbox TTS model available for wake word training"
)
except Exception as e:
logging.warning(f"[WakeWord] Could not get Chatterbox model: {e}")
manager = WakeWordManager(
chatterbox_model=chatterbox_model,
voices_dir=Path(os.getcwd()) / "voices",
)
set_wakeword_manager(manager)
logging.info(
f"[WakeWord] Wake word manager initialized. "
f"Models dir: {manager.models_dir}, "
f"Existing models: {len(manager.list_available_models())}"
)
except Exception as e:
logging.error(f"[WakeWord] Failed to initialize wake word manager: {e}")
@app.on_event("shutdown")
async def shutdown_event():
await request_queue.stop()
# Async wrapper for pipe.get_response
async def process_request_async(data: Dict, completion_type: str):
"""Async wrapper for pipe.get_response to handle it in the queue."""
return await pipe.get_response(data, completion_type)
async def _enqueue_with_fallback(
data: Dict, completion_type: str, request_timeout: float
):
"""Enqueue a request with optional queue-wait fallback routing.
If QUEUE_WAIT_TIMEOUT > 0 and a fallback server is configured:
1. Wait up to QUEUE_WAIT_TIMEOUT for a slot to free up
2. If still queued after that, cancel and forward to fallback server
3. If fallback fails or is unavailable, continue waiting locally
"""
from Pipes import get_fallback_client
from RequestQueue import RequestStatus
queue_wait_timeout = float(getenv("QUEUE_WAIT_TIMEOUT", "30"))
request_id = await request_queue.enqueue_request(
data=data,
completion_type=completion_type,
processor_func=process_request_async,
)
fallback_client = get_fallback_client()
use_fallback = queue_wait_timeout > 0 and fallback_client.is_configured
if not use_fallback:
return await request_queue.wait_for_result(request_id, timeout=request_timeout)
# Two-phase wait: short queue timeout → fallback → remaining timeout
request = request_queue.active_requests.get(request_id)
if not request:
raise HTTPException(status_code=500, detail="Request lost from queue")
# Phase 1: poll the future for queue_wait_timeout seconds without cancelling it
deadline = time.time() + queue_wait_timeout
while time.time() < deadline:
if request.future.done():
break
await asyncio.sleep(0.25)
if request.future.done():
# Completed (or failed) within queue-wait timeout
result = request.future.result()
else:
# Still queued — try fallback if request hasn't started processing
if request.status == RequestStatus.QUEUED:
logging.info(
f"[Queue] Request {request_id} queued >{queue_wait_timeout}s, trying fallback"
)
try:
available, reason = await fallback_client.check_availability()
if available:
is_streaming = data.get("stream", False)
if completion_type == "chat":
fb_response = await fallback_client.forward_chat_completion(
data, stream=is_streaming
)
else:
fb_response = await fallback_client.forward_completion(
data, stream=is_streaming
)
request_queue.cancel_request(request_id)
return fb_response, None
except Exception as e:
logging.warning(
f"[Queue] Fallback failed ({e}), continuing to wait locally"
)
# Fallback failed/unavailable or request already processing — wait remaining time
remaining = max(1.0, request_timeout - queue_wait_timeout)
try:
result = await asyncio.wait_for(request.future, timeout=remaining)
except asyncio.TimeoutError:
request_queue.active_requests.pop(request_id, None)
raise
if request.status == RequestStatus.FAILED:
logging.error(f"[Queue] Request failed: {request.error}")
raise HTTPException(status_code=500, detail="Internal server error")
# Clean up
request_queue.request_history[request_id] = request_queue.active_requests.pop(
request_id, None
)
return result
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
NGROK_TOKEN = getenv("NGROK_TOKEN")
if NGROK_TOKEN:
from pyngrok import ngrok
ngrok.set_auth_token(NGROK_TOKEN)
public_url = ngrok.connect(8091)
logging.info(f"[ngrok] Public Tunnel: {public_url.public_url}")
ngrok_url = public_url.public_url
def get_ngrok_url():
global ngrok_url
return ngrok_url
else:
def get_ngrok_url():
return "http://localhost:8091"
os.makedirs("outputs", exist_ok=True)
app.mount("/outputs", StaticFiles(directory="outputs"), name="outputs")
def verify_api_key(authorization: str = Header(None)):
encryption_key = getenv("EZLOCALAI_API_KEY")
if encryption_key:
if encryption_key == "none":
return "USER"
try:
if "bearer " in authorization.lower():
scheme, _, api_key = authorization.partition(" ")
else:
api_key = authorization
if api_key != encryption_key:
raise HTTPException(status_code=401, detail="Invalid API Key")
return "USER"
except Exception as e:
raise HTTPException(status_code=401, detail="Invalid API Key")
else:
return "USER"
@app.get(
"/v1/models",
tags=["Models"],
dependencies=[Depends(verify_api_key)],
)
async def models(user=Depends(verify_api_key)):
return pipe.get_models()
@app.get("/health", tags=["System"])
async def health_check():
"""Health check for load balancers and container orchestrators."""
if request_queue._task and not request_queue._task.done():
return {"status": "healthy"}
raise HTTPException(status_code=503, detail="Queue processor not running")
@app.get(
"/v1/resources",
tags=["System"],
dependencies=[Depends(verify_api_key)],
)
async def get_resources(user=Depends(verify_api_key)):
"""Get current resource status including VRAM usage, loaded models, and fallback info."""
from Pipes import (
get_resource_manager,
get_fallback_client,
should_use_ezlocalai_fallback,
)
resource_mgr = get_resource_manager()
status = resource_mgr.get_status()
# Add fallback information
fallback_client = get_fallback_client()
should_fallback, fallback_reason = should_use_ezlocalai_fallback()
# Get combined memory info
try:
import psutil
free_ram = psutil.virtual_memory().available / (1024**3)
except ImportError:
free_ram = 0.0
free_vram = resource_mgr.get_total_free_vram()
status["fallback"] = {
"configured": fallback_client.is_configured,
"url": fallback_client.base_url if fallback_client.is_configured else None,
"should_use_fallback": should_fallback,
"reason": fallback_reason,
"free_vram_gb": free_vram,
"free_ram_gb": free_ram,
"free_combined_gb": free_vram + free_ram,
"memory_threshold_gb": float(getenv("FALLBACK_MEMORY_THRESHOLD", "8.0")),
}
# Add parallel inference info
n_parallel = getattr(pipe.llm, "n_parallel", 1) if pipe.llm else 1
n_ctx = getattr(pipe.llm, "xlc_params", None)
n_ctx_val = n_ctx.n_ctx if n_ctx else 0
queue_wait_timeout = float(getenv("QUEUE_WAIT_TIMEOUT", "30"))
status["parallel"] = {
"n_parallel": n_parallel,
"n_ctx": n_ctx_val,
"per_slot_context": n_ctx_val // n_parallel if n_parallel > 0 else n_ctx_val,
"max_concurrent_requests": request_queue.max_concurrent_requests,
"queue_wait_timeout": queue_wait_timeout if queue_wait_timeout > 0 else None,
}
return status
@app.get(
"/v1/fallback/status",
tags=["System"],
dependencies=[Depends(verify_api_key)],
)
async def get_fallback_status(user=Depends(verify_api_key)):
"""Check the status and availability of the fallback ezlocalai server."""
from Pipes import get_fallback_client, should_use_ezlocalai_fallback
fallback_client = get_fallback_client()
if not fallback_client.is_configured:
return {
"configured": False,
"available": False,
"reason": "No fallback server configured",
"should_use": False,
}
available, avail_reason = await fallback_client.check_availability()
should_fallback, fallback_reason = should_use_ezlocalai_fallback()
# Try to get remote models if available
remote_models = []
if available:
try:
models_response = await fallback_client.get_models()
remote_models = [
m.get("id", m.get("name", "unknown"))
for m in models_response.get("data", [])
]
except:
pass
return {
"configured": True,
"url": fallback_client.base_url,
"available": available,
"availability_reason": avail_reason,
"should_use": should_fallback,
"should_use_reason": fallback_reason,
"remote_models": remote_models,
}
@app.get(
"/v1/queue",
tags=["System"],
dependencies=[Depends(verify_api_key)],
)
async def get_queue_status(user=Depends(verify_api_key)):
"""Get current request queue status."""
return request_queue.get_queue_status()
# For the completions and chat completions endpoints, we use extra_json for additional parameters.
# --------------------------------
# If `audio_format`` is present, the prompt will be transcribed to text.
# It is assumed it is base64 encoded audio in the `audio_format`` specified.
# --------------------------------
# If `system_message`` is present, it will be used as the system message for the completion.
# --------------------------------
# If `voice`` is present, the completion will be converted to audio using the specified voice.
# If not streaming, the audio will be returned in the response in the "audio" beside the "text" or "content" keys.
# If streaming, the audio will be streamed in the response in audio/wav format.
# Chat completions endpoint
# https://platform.openai.com/docs/api-reference/chat
class ChatCompletions(BaseModel):
model: str = DEFAULT_MODEL
messages: List[dict] = None
temperature: Optional[float] = 0.9
top_p: Optional[float] = 1.0
functions: Optional[List[dict]] = None
function_call: Optional[str] = None
n: Optional[int] = 1
stream: Optional[bool] = False
stop: Optional[List[str]] = None
max_tokens: Optional[int] = 8192
presence_penalty: Optional[float] = 0.0
frequency_penalty: Optional[float] = 0.0
logit_bias: Optional[Dict[str, float]] = None
user: Optional[str] = None
chat_template_kwargs: Optional[Dict[str, Any]] = None
class ChatCompletionsResponse(BaseModel):
id: str
object: str
created: int
model: str
choices: List[dict]
usage: dict
@app.post(
"/v1/chat/completions",
tags=["Completions"],
dependencies=[Depends(verify_api_key)],
)
async def chat_completions(
c: ChatCompletions, request: Request, user=Depends(verify_api_key)
):
# Check if text server is configured - forward if so
from Pipes import get_text_server_client
text_client = get_text_server_client()
if text_client.is_configured:
available, _ = await text_client.check_availability()
if available:
data = await request.json()
logging.info("[Chat] Forwarding to text server")
try:
result = await text_client.forward_chat_completions(data)
if result is not None:
return result
except Exception as e:
logging.warning(f"[Chat] Text server forward failed: {e}, using local")
if getenv("DEFAULT_MODEL") or getenv("VISION_MODEL"):
data = await request.json()
# Ensure max_tokens has a sensible default when not provided by client.
# Without this, LLM.chat() falls back to self.params["max_tokens"] which
# equals the context size (LLM_MAX_TOKENS), causing the model to generate
# up to 40K output tokens per request (runaway generation).
if "max_tokens" not in data:
data["max_tokens"] = c.max_tokens # Pydantic default: 8192
# Add request timeout (configurable via environment variable)
request_timeout = float(getenv("REQUEST_TIMEOUT", "300")) # 5 minutes default
try:
response, audio_response = await _enqueue_with_fallback(
data=data,
completion_type="chat",
request_timeout=request_timeout,
)
except HTTPException:
# Re-raise HTTP exceptions (queue full, etc.)
raise
except asyncio.TimeoutError:
raise HTTPException(
status_code=408,
detail=f"Request timed out after {request_timeout} seconds",
)
except Exception as e:
logging.error(f"[Chat Completions] Unexpected error: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
if audio_response:
if audio_response.startswith("http"):
return response
if not c.stream:
return response
else:
if audio_response:
return StreamingResponse(
content=audio_response,
media_type="audio/wav",
)
# Create a generator that yields properly formatted SSE chunks
def generate_stream():
try:
import json
chunk_count = 0
for chunk in response:
chunk_count += 1
yield f"data: {json.dumps(chunk)}\n\n"
logging.debug(f"[STREAMING] Finished {chunk_count} chunks")
yield "data: [DONE]\n\n"
except Exception as e:
import traceback
logging.error(f"[STREAMING] Streaming error: {e}")
logging.error(
f"[STREAMING] Full traceback: {traceback.format_exc()}"
)
# Don't expose exception details to client
yield f'data: {{"error": "Streaming failed"}}\n\n'
finally:
# Close the underlying response generator so that
# GeneratorExit propagates down to LLM._chat_stream(),
# which sets cancel_event and frees the inference slot.
if hasattr(response, "close"):
response.close()
return StreamingResponse(
content=generate_stream(),
media_type="text/event-stream",
)
else:
raise HTTPException(status_code=404, detail="Chat completions are disabled.")
# Completions endpoint
# https://platform.openai.com/docs/api-reference/completions
class Completions(BaseModel):
model: str = DEFAULT_MODEL
prompt: str = ""
max_tokens: Optional[int] = 8192
temperature: Optional[float] = 0.9
top_p: Optional[float] = 1.0
n: Optional[int] = 1
stream: Optional[bool] = False
logit_bias: Optional[Dict[str, float]] = None
stop: Optional[List[str]] = None
echo: Optional[bool] = False
user: Optional[str] = None
format_prompt: Optional[bool] = True
class CompletionsResponse(BaseModel):
id: str
object: str
created: int
model: str
choices: List[dict]
usage: dict
@app.post(
"/v1/completions",
tags=["Completions"],
dependencies=[Depends(verify_api_key)],
)
async def completions(c: Completions, request: Request, user=Depends(verify_api_key)):
# Check if text server is configured - forward if so
from Pipes import get_text_server_client
text_client = get_text_server_client()
if text_client.is_configured:
available, _ = await text_client.check_availability()
if available:
data = await request.json()
logging.info("[Completions] Forwarding to text server")
try:
result = await text_client.forward_completions(data)
if result is not None:
return result
except Exception as e:
logging.warning(
f"[Completions] Text server forward failed: {e}, using local"
)
if getenv("DEFAULT_MODEL") or getenv("VISION_MODEL"):
data = await request.json()
# Ensure max_tokens has a sensible default when not provided by client.
if "max_tokens" not in data:
data["max_tokens"] = c.max_tokens # Pydantic default: 8192
# Add request timeout (configurable via environment variable)
request_timeout = float(getenv("REQUEST_TIMEOUT", "300")) # 5 minutes default
try:
response, audio_response = await _enqueue_with_fallback(
data=data,
completion_type="completion",
request_timeout=request_timeout,
)
except HTTPException:
# Re-raise HTTP exceptions (queue full, etc.)
raise
except asyncio.TimeoutError:
raise HTTPException(
status_code=408,
detail=f"Request timed out after {request_timeout} seconds",
)
except Exception as e:
logging.error(f"[Completions] Unexpected error: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
if audio_response:
if audio_response.startswith("http"):
return response
if not c.stream:
return response
else:
if audio_response:
return StreamingResponse(
content=audio_response,
media_type="audio/wav",
)
return StreamingResponse(
content=response["choices"][0]["text"],
media_type="text/event-stream",
)
else:
raise HTTPException(status_code=404, detail="Completions are disabled.")
# Embeddings endpoint
# https://platform.openai.com/docs/api-reference/embeddings
class EmbeddingModel(BaseModel):
input: Union[str, List[str]]
model: Optional[str] = DEFAULT_MODEL
user: Optional[str] = None
class EmbeddingResponse(BaseModel):
object: str
data: List[dict]
model: str
usage: dict
@app.post(
"/v1/embeddings",
tags=["Embeddings"],
dependencies=[Depends(verify_api_key)],
)
async def embedding(embedding: EmbeddingModel, user=Depends(verify_api_key)):
# Check if text server is configured - forward if so
from Pipes import get_text_server_client
text_client = get_text_server_client()
if text_client.is_configured:
available, _ = await text_client.check_availability()
if available:
logging.info("[Embeddings] Forwarding to text server")
try:
result = await text_client.forward_embeddings(
{"input": embedding.input, "model": embedding.model}
)
if result is not None:
return result
except Exception as e:
logging.warning(
f"[Embeddings] Text server forward failed: {e}, using local"
)
from Pipes import should_use_ezlocalai_fallback, get_fallback_client
# Check if we should use fallback
should_fallback, reason = should_use_ezlocalai_fallback()
if should_fallback:
fallback_client = get_fallback_client()
if fallback_client.is_configured:
available, _ = await fallback_client.check_availability()
if available:
logging.info(f"[Embeddings] Using fallback: {reason}")
try:
return await fallback_client.forward_embeddings(
{
"input": embedding.input,
"model": embedding.model,
}
)
except Exception as e:
logging.warning(f"[Embeddings] Fallback failed: {e}, using local")
# Use local embeddings
async with pipe._embedder_lock:
embedder = pipe._get_embedder()
result = embedder.get_embeddings(input=embedding.input)
pipe._destroy_embedder()
return result
# Audio Transcription endpoint
# https://platform.openai.com/docs/api-reference/audio/createTranscription
@app.post(
"/v1/audio/transcriptions",
tags=["Audio"],
dependencies=[Depends(verify_api_key)],
)
async def speech_to_text(
file: UploadFile = File(...),
model: str = Form(WHISPER_MODEL),
language: Optional[str] = Form(None),
prompt: Optional[str] = Form(None),
response_format: Optional[str] = Form("json"),
temperature: Optional[float] = Form(0.0),
timestamp_granularities: Optional[List[str]] = Form(["segment"]),
enable_diarization: Optional[bool] = Form(False),
num_speakers: Optional[int] = Form(None),
session_id: Optional[str] = Form(None),
user: str = Depends(verify_api_key),
):
if getenv("STT_ENABLED").lower() == "false":
raise HTTPException(status_code=404, detail="Speech to text is disabled.")
from Pipes import get_voice_server_client, is_voice_server_mode
# Read file content first (before any fallback attempts)
file_content = await file.read()
# Try voice server first if configured (not in voice server mode)
if not is_voice_server_mode():
voice_client = get_voice_server_client()
if voice_client.is_configured:
available, reason = await voice_client.check_availability()
if available:
logging.info(
f"[STT] Forwarding to voice server: {voice_client.base_url}"
)
response = await voice_client.forward_transcription(
file_content=file_content,
content_type=file.content_type,
model=model,
language=language,
prompt=prompt,
response_format=response_format,
temperature=temperature,
)
if response:
# Return the response as-is from voice server
if response_format == "text":
text_content = response.get("text", str(response))
return Response(content=text_content, media_type="text/plain")
return response
logging.warning("[STT] Voice server failed, falling back to local")
from Pipes import should_use_ezlocalai_fallback, get_fallback_client
# Check if we should use fallback (general fallback server)
should_fallback, reason = should_use_ezlocalai_fallback()
if should_fallback:
fallback_client = get_fallback_client()
if fallback_client.is_configured:
available, _ = await fallback_client.check_availability()
if available:
logging.info(f"[STT] Using fallback: {reason}")
try:
response = await fallback_client.forward_transcription(
file_content=file_content,
content_type=file.content_type,
model=model,
language=language,
prompt=prompt,
response_format=response_format,
temperature=temperature,
)
# Return the response as-is from fallback
if response_format == "text":
text_content = response.get("text", str(response))
return Response(content=text_content, media_type="text/plain")
return response
except Exception as e:
logging.warning(f"[STT] Fallback failed: {e}, using local")
async with pipe._stt_lock:
stt = pipe._get_stt()
# Determine if we need segments based on response_format or diarization
need_segments = (
response_format in ["verbose_json", "srt", "vtt"] or enable_diarization
)
response = await stt.transcribe_audio(
base64_audio=base64.b64encode(file_content).decode("utf-8"),
audio_format=file.content_type,
language=language,
prompt=prompt,
temperature=temperature,
return_segments=need_segments,
enable_diarization=enable_diarization,
num_speakers=num_speakers,
session_id=session_id,
)
# In voice server mode, don't destroy STT - keep it loaded
if not is_voice_server_mode():
pipe._destroy_stt()
# Format response based on response_format
if response_format == "text":
text_content = response["text"] if isinstance(response, dict) else response
return Response(content=text_content, media_type="text/plain")
elif response_format == "verbose_json":
# Already in correct format with segments
return response
elif response_format == "srt":
srt_content = segments_to_srt(response["segments"])
return Response(content=srt_content, media_type="text/plain")
elif response_format == "vtt":
vtt_content = segments_to_vtt(response["segments"])
return Response(content=vtt_content, media_type="text/vtt")
else: # json (default)
if isinstance(response, dict):
return {"text": response["text"]}
return {"text": response}
# Audio Translation endpoint
# https://platform.openai.com/docs/api-reference/audio/createTranslation
@app.post(
"/v1/audio/translations",
tags=["Audio"],
dependencies=[Depends(verify_api_key)],
)
async def audio_translations(
file: UploadFile = File(...),
model: str = Form(WHISPER_MODEL),
language: Optional[str] = Form(None),
prompt: Optional[str] = Form(None),
response_format: Optional[str] = Form("json"),
temperature: Optional[float] = Form(0.0),
user=Depends(verify_api_key),
):
if getenv("STT_ENABLED").lower() == "false":
raise HTTPException(status_code=404, detail="Speech to text is disabled.")
from Pipes import is_voice_server_mode
async with pipe._stt_lock:
stt = pipe._get_stt()
response = await stt.transcribe_audio(
base64_audio=base64.b64encode(await file.read()).decode("utf-8"),
audio_format=file.content_type,
language=language,
prompt=prompt,
temperature=temperature,
translate=True,
)
# In voice server mode, don't destroy STT - keep it loaded
if not is_voice_server_mode():
pipe._destroy_stt()
return {"text": response}
# Helper function for batch translating subtitle segments
async def translate_segments_batch(
segments: list, source_lang: str, target_lang: str, max_words: int = 4000
) -> list:
"""
Translate multiple subtitle segments using the LLM in batches.
Batches are sized by word count (~4000 words) to stay within context limits
while minimizing the number of API calls.
"""
translated_segments = []
# Build batches based on word count, not fixed segment count
batches = []
current_batch = []
current_word_count = 0
for seg in segments:
seg_words = len(seg["text"].split())
if current_word_count + seg_words > max_words and current_batch:
batches.append(current_batch)
current_batch = []
current_word_count = 0
current_batch.append(seg)
current_word_count += seg_words
if current_batch:
batches.append(current_batch)
logging.info(
f"Translating {len(segments)} segments in {len(batches)} batches (~{max_words} words each)"
)
for batch_idx, batch in enumerate(batches):
# Build numbered text block for batch translation
text_block = "\n".join(
[f"[{j+1}] {seg['text']}" for j, seg in enumerate(batch)]
)
messages = [
{
"role": "system",
"content": f"""You are a professional subtitle translator. Translate the numbered subtitle lines from {source_lang} to {target_lang}.
Keep translations concise and natural for subtitles.
Maintain the exact same numbering format [N] for each line.
Return ONLY the translated lines with their numbers, nothing else.""",
},
{"role": "user", "content": text_block},
]
# Call LLM for batch translation
response, _ = await pipe.get_response(
data={
"model": getenv("DEFAULT_MODEL"),
"messages": messages,
},
completion_type="chat",
)
# Parse response and map back to segments
translated_text = ""
if isinstance(response, dict) and "choices" in response:
translated_text = response["choices"][0]["message"]["content"].strip()
# Parse the numbered responses
translations = {}
for line in translated_text.split("\n"):
match = re.match(r"\[(\d+)\]\s*(.+)", line.strip())
if match:
num = int(match.group(1))
text = match.group(2).strip()
translations[num] = text
# Map translations back to segments
for j, seg in enumerate(batch):
translated_segments.append(
{
"id": seg["id"],
"start": seg["start"],
"end": seg["end"],
"text": translations.get(