Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 43 additions & 9 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -15,30 +15,63 @@ DJANGO_CSRF_TRUSTED_ORIGINS=http://localhost:8000
CORS_ALLOW_ALL_ORIGINS=true
CORS_ALLOWED_ORIGINS=http://localhost:8000,https://npc.metarang.com
DJANGO_PORT=8000
VECTOR_STORE_MAX_FILES=10
VECTOR_STORE_MAX_RSS_LINKS=10
VECTOR_STORE_MAX_UPLOAD_BYTES=26214400
VOICE_SAMPLE_MAX_UPLOAD_BYTES=26214400
VOICE_SAMPLE_MIN_DURATION_SECONDS=1
VOICE_SAMPLE_MAX_DURATION_SECONDS=60
VOICE_SAMPLE_MIN_VOICED_SECONDS=0.8
VOICE_SAMPLE_PROCESSING_TIMEOUT_SECONDS=30
VC_SAMPLE_VALIDATION_TIMEOUT_SECONDS=3

# Existing AI models. Paths are host paths mounted read-only into containers.
WHISPER_MODEL=turbo
WHISPER_DEVICE=auto
# AI models. Paths are host paths mounted read-only into containers.
WHISPER_MODEL=large
# The single STT microservice serves LiveKit, /record/, and the WebSocket test page.
# Django itself does not receive GPU access or load a second Whisper instance.
WHISPER_DEVICE=cuda
EMBEDDING_MODEL_PATH_HOST=/home/npc/Documents/Fine-tune-LLM/models/sentence_embeddings
LLM_MODEL=dorna2
LLM_USE_GPU=true
TTS_MODEL_PATH_HOST=./TTS/best_model_91323.pth
VC_MODEL_PATH_HOST=./VC/freevc.pth
VC_WAVLM_PATH_HOST=./VC/wavlm/WavLM-Large.pt
VC_SPEAKER_ENCODER_PATH_HOST=./VC/speaker_encoder/ckpt/pretrained_bak_5805000.pt
TTS_MODEL_DIR_HOST=./TTS/models/mana
TTS_CPU_THREADS=4
# Offline speech normalization. Custom entries override the bundled lexicon.
TTS_DIACRITIZATION=lexicon
TTS_PRONUNCIATION_DIR_HOST=./TTS/pronunciation
TTS_MAX_NORMALIZED_TEXT_LENGTH=12000
VC_CHECKPOINT_DIR_HOST=./VC/checkpoints/openvoice-v2
# One P40 was verified on this host, so index 0 is unambiguous inside the container.
VC_GPU_DEVICE=0

# Pipeline concurrency, endpointing, and failure policy.
STT_QUEUE_SIZE=8
STT_INFERENCE_WORKERS=1
STT_TIMEOUT_SECONDS=120
TTS_TIMEOUT_SECONDS=120
VC_TIMEOUT_SECONDS=120
LLM_MAX_CONCURRENT_REQUESTS=2
LLM_STREAM_QUEUE_SIZE=32
LLM_TIMEOUT_SECONDS=180
LLM_OPERATION_TIMEOUT_SECONDS=600
OLLAMA_REQUEST_TIMEOUT_SECONDS=180
REDIS_SOCKET_TIMEOUT_SECONDS=5
SPEECH_THRESHOLD_DBFS=38
SPEECH_END_SILENCE_MS=900
SENTENCE_QUEUE_SIZE=2
PARTICIPANT_WAIT_TIMEOUT_SECONDS=45
VC_FAILURE_FALLBACK=true
VC_FAILURE_FALLBACK=false
SPEECH_JOB_RETENTION_SECONDS=3600
SPEECH_TEXT_MAX_LENGTH=2000
VC_MAX_CONCURRENT_REQUESTS=1
VC_QUEUE_MAX_SIZE=4
VC_QUEUE_TIMEOUT_SECONDS=30
VC_TARGET_CACHE_MAX_ENTRIES=32
VC_TARGET_CACHE_TTL_SECONDS=1800
# Measured OpenVoice peak (253 MiB) plus the 512 MiB safety margin on Tesla P40.
VC_MIN_FREE_VRAM_MB=765
VC_VRAM_SAFETY_MARGIN_MB=512
VC_MODEL_RETRY_COOLDOWN_SECONDS=30
VC_MIN_VOICED_SECONDS=0.8

# Local observability. Change Grafana credentials outside development.
LOG_LEVEL=INFO
Expand All @@ -51,5 +84,6 @@ PROMETHEUS_PORT=9091
API_DOMAIN=npc.metarang.com
LIVEKIT_DOMAIN=livekit.example.com
LIVEKIT_TURN_DOMAIN=turn.example.com
LIVEKIT_NODE_IP=203.0.113.10
# Required for remote WebRTC clients; leave empty only for localhost-only use.
LIVEKIT_NODE_IP=
TLS_CERTS_DIR=./certs
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
.vscode/
.claude/
.agents/
.gpu-recovery/

# Python and Django runtime files
__pycache__/
Expand All @@ -25,6 +26,11 @@ nohup.out
*.safetensors
*.wav
*.webp
models/speech/
TTS/models/
VC/checkpoints/
artifacts/benchmarks/*.json
artifacts/benchmarks/*.wav

# Local tooling artifacts
skills-lock.json
Expand Down
220 changes: 220 additions & 0 deletions AgentAPI/serializers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
from __future__ import annotations

from pathlib import Path

from rest_framework import serializers

from .voice_samples import SUPPORTED_VOICE_SAMPLE_EXTENSIONS


SUPPORTED_VECTOR_STORE_EXTENSIONS = (".csv", ".docx", ".pdf", ".txt")


class AgentSessionCreateSerializer(serializers.Serializer):
user_id = serializers.RegexField(
Expand Down Expand Up @@ -42,6 +49,219 @@ class ErrorSerializer(serializers.Serializer):
code = serializers.CharField()


class VoiceSampleCreateSerializer(serializers.Serializer):
name = serializers.CharField(
max_length=64,
help_text="Human-readable label for the target voice.",
)
audio = serializers.FileField(
help_text="A WAV, MP3, M4A, OGG, FLAC, or WebM voice recording.",
)

def validate_audio(self, audio):
suffix = Path(audio.name).suffix.lower()
if suffix not in SUPPORTED_VOICE_SAMPLE_EXTENSIONS:
supported = ", ".join(SUPPORTED_VOICE_SAMPLE_EXTENSIONS)
raise serializers.ValidationError(f"Unsupported audio type. Supported: {supported}.")
if not audio.size:
raise serializers.ValidationError("The audio recording is empty.")
max_bytes = self.context["max_bytes"]
if audio.size > max_bytes:
max_megabytes = max_bytes // (1024 * 1024)
raise serializers.ValidationError(
f"The audio recording exceeds the {max_megabytes} MB limit."
)
return audio


class VoiceSampleResponseSerializer(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField()
filename = serializers.CharField(
help_text="Internal normalized WAV filename used by the voice-conversion service."
)
audio_url = serializers.CharField()
created_at = serializers.DateTimeField()


class VoiceSampleListSerializer(serializers.Serializer):
samples = VoiceSampleResponseSerializer(many=True)
count = serializers.IntegerField()


class VoiceSampleDeleteSerializer(serializers.Serializer):
id = serializers.IntegerField()
status = serializers.CharField()


class SpeechJobCreateSerializer(serializers.Serializer):
text = serializers.CharField(
trim_whitespace=True,
help_text="Persian text synthesized by the CPU-only Mana Piper service.",
)
sample_id = serializers.IntegerField(
required=False,
min_value=1,
help_text="ID of a previously uploaded persistent target voice sample.",
)
voice_sample_id = serializers.IntegerField(
required=False,
min_value=1,
help_text="Deprecated alias for sample_id; retained for backward compatibility.",
)
reference_audio = serializers.FileField(
required=False,
help_text=(
"Temporary target-voice recording. It is normalized in memory, sent to OpenVoice, "
"and never added to the persistent voice-sample library."
),
)
tau = serializers.FloatField(required=False, default=0.3, min_value=0.0, max_value=1.0)
length_scale = serializers.FloatField(required=False, min_value=0.5, max_value=2.0)
noise_scale = serializers.FloatField(required=False, min_value=0.0, max_value=2.0)
noise_w = serializers.FloatField(required=False, min_value=0.0, max_value=2.0)

def validate_reference_audio(self, audio):
suffix = Path(audio.name).suffix.lower()
if suffix not in SUPPORTED_VOICE_SAMPLE_EXTENSIONS:
supported = ", ".join(SUPPORTED_VOICE_SAMPLE_EXTENSIONS)
raise serializers.ValidationError(f"Unsupported audio type. Supported: {supported}.")
if not audio.size:
raise serializers.ValidationError("The reference recording is empty.")
max_bytes = self.context["max_bytes"]
if audio.size > max_bytes:
max_megabytes = max_bytes // (1024 * 1024)
raise serializers.ValidationError(
f"The reference recording exceeds the {max_megabytes} MB limit."
)
return audio

def validate_text(self, value: str) -> str:
if len(value) > self.context["max_text_length"]:
raise serializers.ValidationError(
f"Text must not exceed {self.context['max_text_length']} characters."
)
return value

def validate(self, attrs):
persistent_ids = int("sample_id" in attrs) + int("voice_sample_id" in attrs)
if persistent_ids > 1:
raise serializers.ValidationError(
"Provide sample_id only; voice_sample_id is its backward-compatible alias."
)
targets = int(persistent_ids == 1) + int("reference_audio" in attrs)
if targets != 1:
raise serializers.ValidationError(
"Provide exactly one of sample_id or reference_audio."
)
if "sample_id" in attrs:
attrs["voice_sample_id"] = attrs.pop("sample_id")
return attrs


class SpeechJobResponseSerializer(serializers.Serializer):
job_id = serializers.UUIDField()
status = serializers.ChoiceField(choices=("completed", "completed_with_fallback"))
conversion_status = serializers.ChoiceField(choices=("completed", "fallback"))
fallback_used = serializers.BooleanField()
source_audio_url = serializers.CharField()
converted_audio_url = serializers.CharField(allow_null=True)
metrics = serializers.DictField()
expires_at = serializers.DateTimeField()


class VectorStoreCreateSerializer(serializers.Serializer):
user_id = serializers.RegexField(
r"^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$",
help_text=(
"Stable application user ID. The resulting store identifier can be used "
"when creating an agent session for this user."
),
)
files = serializers.ListField(
child=serializers.FileField(),
allow_empty=False,
help_text="One or more PDF, DOCX, TXT, or CSV knowledge files.",
)

def validate_files(self, files):
max_files = self.context["max_files"]
max_file_bytes = self.context["max_file_bytes"]
if len(files) > max_files:
raise serializers.ValidationError(f"At most {max_files} files may be uploaded at once.")

for uploaded_file in files:
filename = uploaded_file.name.lower()
if not filename.endswith(SUPPORTED_VECTOR_STORE_EXTENSIONS):
supported = ", ".join(SUPPORTED_VECTOR_STORE_EXTENSIONS)
raise serializers.ValidationError(
f"Unsupported file type for '{uploaded_file.name}'. Supported: {supported}."
)
if uploaded_file.size > max_file_bytes:
max_megabytes = max_file_bytes // (1024 * 1024)
raise serializers.ValidationError(
f"'{uploaded_file.name}' exceeds the {max_megabytes} MB limit."
)
return files


class VectorStoreResponseSerializer(serializers.Serializer):
user_id = serializers.CharField()
vector_store = serializers.CharField(
help_text="Pass this value as vector_store when creating an agent session."
)
ready = serializers.BooleanField()
created = serializers.BooleanField()
files_received = serializers.IntegerField(required=False)
rss_links_received = serializers.IntegerField(required=False)
documents_added = serializers.IntegerField()
message = serializers.CharField()


class VectorStoreRSSCreateSerializer(serializers.Serializer):
user_id = serializers.RegexField(
r"^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$",
help_text="Stable application user ID that owns the resulting vector store.",
)
rss_link = serializers.URLField(
required=False,
help_text="A single RSS or Atom feed URL.",
)
rss_links = serializers.ListField(
child=serializers.URLField(),
required=False,
allow_empty=False,
help_text="One or more RSS or Atom feed URLs.",
)

def validate(self, attrs):
links = list(attrs.get("rss_links", []))
single_link = attrs.pop("rss_link", None)
if single_link:
links.append(single_link)

# Preserve request order while avoiding duplicate crawling work.
links = list(dict.fromkeys(links))
if not links:
raise serializers.ValidationError(
{"rss_links": "Provide rss_link or at least one item in rss_links."}
)
max_links = self.context["max_links"]
if len(links) > max_links:
raise serializers.ValidationError(
{"rss_links": f"At most {max_links} RSS links may be processed at once."}
)
attrs["rss_links"] = links
return attrs


class VectorStoreStatusSerializer(serializers.Serializer):
user_id = serializers.CharField()
vector_store = serializers.CharField()
ready = serializers.BooleanField()
dataset_exists = serializers.BooleanField()


class HealthSerializer(serializers.Serializer):
status = serializers.ChoiceField(choices=("ok", "not_ready"))
service = serializers.CharField()
Expand Down
Loading
Loading