feat: fix frontend and activate imports

This commit is contained in:
2026-03-17 13:53:12 -03:00
parent be699ad6ab
commit 31939e31ad
24 changed files with 34 additions and 2117 deletions
-69
View File
@@ -1,69 +0,0 @@
#!/bin/bash
# Check and start Bark TTS service on t-800
echo "=== Checking Bark TTS Status on t-800 ==="
echo ""
# Check if systemd service exists
if systemctl list-unit-files | grep -q bark-tts; then
echo "✅ Bark systemd service found"
# Check service status
echo ""
echo "Service Status:"
sudo systemctl status bark-tts --no-pager
# If not running, try to start
if ! systemctl is-active --quiet bark-tts; then
echo ""
echo "⚠️ Service is not running. Attempting to start..."
sudo systemctl start bark-tts
sleep 5
if systemctl is-active --quiet bark-tts; then
echo "✅ Service started successfully!"
else
echo "❌ Failed to start service. Checking logs..."
echo ""
echo "Recent logs:"
sudo journalctl -u bark-tts -n 20 --no-pager
fi
else
echo "✅ Service is running"
fi
else
echo "❌ Bark systemd service not found"
echo ""
echo "The installation may not have completed successfully."
echo "Check if Bark is installed manually:"
echo ""
echo " ls -la /opt/bark/bark/"
echo " ps aux | grep uvicorn"
echo ""
echo "To install manually, run:"
echo " ssh juan@t-800"
echo " sudo /tmp/install_bark_tts.sh (if script exists)"
echo ""
fi
# Test API if service is running
if systemctl is-active --quiet bark-tts; then
echo ""
echo "=== Testing Bark API ==="
# Health check
echo "Health endpoint:"
curl -s http://localhost:8443/health | head -5
echo ""
echo ""
echo "Voices endpoint:"
curl -s http://localhost:8443/api/voices | head -10
echo ""
echo ""
echo "=== API is accessible ==="
echo "You can now generate audio with:"
echo " curl 'http://localhost:8443/api/generate?text=Hello%20World&voice=v2/en_speaker_1' -o test.wav"
fi
-193
View File
@@ -1,193 +0,0 @@
#!/bin/bash
# Bark TTS Cleanup Script for t-800
# This script removes all Bark TTS components from the server
set -e
T800_HOST="t-800"
T800_USER="juan"
echo "=========================================="
echo " Bark TTS Cleanup for t-800"
echo "=========================================="
echo ""
echo "This script will completely remove Bark TTS from t-800"
echo "Including:"
echo " - Systemd service"
echo " - Installation directory (/opt/bark)"
echo " - User account (bark)"
echo " - All cached models (~3.6 GB)"
echo ""
read -p "Continue? [y/N]: " confirm
if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
echo "❌ Cancelled"
exit 0
fi
echo ""
echo "📤 Copying cleanup script to t-800..."
# Create cleanup script
cat > /tmp/cleanup_bark_remote.sh << 'INNEREOF'
#!/bin/bash
set -e
echo ""
echo "=== Stopping Bark Service ==="
sudo systemctl stop bark-tts 2>/dev/null && echo "✅ Service stopped" || echo "⚠️ Service not running"
echo ""
echo "=== Disabling Bark Service ==="
sudo systemctl disable bark-tts 2>/dev/null && echo "✅ Service disabled" || echo "⚠️ Service not enabled"
echo ""
echo "=== Removing Systemd Service ==="
if [ -f /etc/systemd/system/bark-tts.service ]; then
sudo rm -f /etc/systemd/system/bark-tts.service
sudo systemctl daemon-reload
echo "✅ Systemd service removed"
else
echo "⚠️ Systemd service not found"
fi
echo ""
echo "=== Removing Installation Directory ==="
if [ -d /opt/bark ]; then
SIZE=$(du -sh /opt/bark 2>/dev/null | cut -f1)
echo "📊 Directory size: $SIZE"
sudo rm -rf /opt/bark
echo "✅ Directory removed"
else
echo "⚠️ Directory /opt/bark not found"
fi
echo ""
echo "=== Removing User Account ==="
if id bark &>/dev/null; then
sudo userdel -r bark 2>/dev/null && echo "✅ User removed" || echo "⚠️ Could not remove user"
else
echo "⚠️ User 'bark' does not exist"
fi
echo ""
echo "=== Cleaning Python Cache ==="
sudo rm -rf /root/.cache/pip 2>/dev/null || true
echo "✅ Cache cleaned"
echo ""
echo "=========================================="
echo " Verification"
echo "=========================================="
echo ""
echo "Services:"
if systemctl list-unit-files 2>/dev/null | grep -q bark; then
echo "❌ Bark services still exist:"
systemctl list-unit-files 2>/dev/null | grep bark
else
echo "✅ No Bark services found"
fi
echo ""
echo "Directories:"
if [ -d /opt/bark ]; then
echo "❌ Directory still exists: /opt/bark"
else
echo "✅ No Bark directories found"
fi
echo ""
echo "Users:"
if id bark &>/dev/null 2>&1; then
echo "❌ User 'bark' still exists"
else
echo "✅ User 'bark' removed"
fi
echo ""
echo "Processes:"
if ps aux | grep -v grep | grep -q "bark_api"; then
echo "❌ Bark processes still running"
ps aux | grep -v grep | grep "bark_api"
else
echo "✅ No Bark processes running"
fi
echo ""
echo "Ports:"
if sudo netstat -tlnp 2>/dev/null | grep -q 8443; then
echo "❌ Port 8443 still in use"
sudo netstat -tlnp 2>/dev/null | grep 8443
else
echo "✅ Port 8443 is free"
fi
echo ""
echo "Disk Space Recovered:"
echo "Previous: $(df -h /opt 2>/dev/null | tail -1 | awk '{print $4}') available"
echo ""
echo "=========================================="
echo " ✅ Cleanup Complete!"
echo "=========================================="
echo ""
echo "Next steps:"
echo " 1. Verify disk space: df -h"
echo " 2. Check available ports: sudo netstat -tlnp"
echo " 3. Continue with OpenCCB features"
echo ""
INNEREOF
# Copy to t-800
scp /tmp/cleanup_bark_remote.sh ${T800_USER}@${T800_HOST}:/tmp/cleanup_bark_remote.sh
echo ""
echo "🔌 Connecting to t-800 and running cleanup..."
echo ""
# Execute on t-800
ssh -t ${T800_USER}@${T800_HOST} << 'ENDSSH'
chmod +x /tmp/cleanup_bark_remote.sh
sudo /tmp/cleanup_bark_remote.sh
# Clean up temp file
rm /tmp/cleanup_bark_remote.sh
ENDSSH
echo ""
echo "=========================================="
echo " Local Cleanup Complete"
echo "=========================================="
echo ""
# Clean up local temp file
rm -f /tmp/cleanup_bark_remote.sh
echo "✅ All Bark TTS components have been removed from t-800"
echo ""
echo "📊 Next Steps - Choose What to Do Next:"
echo ""
echo " 1️⃣ Question Bank (sin audio)"
echo " - Crear preguntas manualmente"
echo " - Importar desde MySQL"
echo " - Generar con IA"
echo " - Acceder: /question-bank"
echo ""
echo " 2️⃣ Token Usage Dashboard"
echo " - Ver consumo de IA por usuario"
echo " - Monitorear costos"
echo " - Detectar alto consumo"
echo " - Acceder: /admin/token-usage"
echo ""
echo " 3️⃣ Importar Preguntas desde MySQL"
echo " - Traer preguntas del sistema legacy"
echo " - Marcar para no duplicar"
echo " - Asignar skills automáticamente"
echo ""
echo "💡 Recommended: Try all three!"
echo ""
echo " cd /home/juan/dev/openccb"
echo " # Start Studio"
echo " cd web/studio && npm run dev"
echo ""
-93
View File
@@ -1,93 +0,0 @@
#!/bin/bash
# Deploy Bark TTS to t-800 server
# Usage: ./deploy_to_t800.sh
set -e
T800_HOST="t-800"
T800_USER="juan"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "=========================================="
echo " Deploying Bark TTS to t-800"
echo "=========================================="
echo ""
# Check if SSH key exists
if [ ! -f ~/.ssh/id_rsa.pub ]; then
echo "SSH key not found. Generating one..."
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N "" -C "openccb_bark_deployment"
echo ""
echo "Now copy your SSH key to t-800:"
echo " ssh-copy-id ${T800_USER}@${T800_HOST}"
echo ""
read -p "Press Enter after copying the key..."
fi
# Copy installation script to t-800
echo "Copying installation script to t-800..."
scp "${SCRIPT_DIR}/install_bark_tts.sh" ${T800_USER}@${T800_HOST}:/tmp/install_bark_tts.sh
# Execute installation on t-800 with pseudo-terminal
echo ""
echo "Connecting to t-800 and installing Bark TTS..."
echo "This may take 10-15 minutes depending on internet speed..."
echo "You'll be prompted for your password..."
echo ""
ssh -t ${T800_USER}@${T800_HOST} << 'ENDSSH'
echo "Connected to t-800"
echo "Hostname: $(hostname)"
echo "Memory: $(free -h | grep Mem | awk '{print $2}')"
echo "Disk: $(df -h / | tail -1 | awk '{print $4}') available"
echo ""
# Install jq if not present
if ! command -v jq &> /dev/null; then
echo "Installing jq..."
sudo apt-get update && sudo apt-get install -y jq
fi
# Make script executable and run
chmod +x /tmp/install_bark_tts.sh
echo "Running Bark installation..."
sudo /tmp/install_bark_tts.sh
# Clean up
rm /tmp/install_bark_tts.sh
# Wait for service to be ready
echo ""
echo "Waiting for Bark API to be ready..."
sleep 10
# Test the API
echo "Testing Bark API..."
if curl -s http://localhost:8443/health | jq . > /dev/null 2>&1; then
echo "✅ Bark API is running!"
curl -s http://localhost:8443/health | jq .
else
echo "⚠️ API may still be starting up..."
echo "Check status with: sudo systemctl status bark-tts"
echo "View logs with: sudo journalctl -u bark-tts -f"
fi
echo ""
echo "Bark TTS installation complete on t-800!"
ENDSSH
echo ""
echo "=========================================="
echo " Deployment Complete!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Add BARK_API_URL to your .env file:"
echo " BARK_API_URL=http://t-800:8443"
echo ""
echo "2. Test the API:"
echo " curl 'http://t-800:8443/api/generate?text=Hello%20World&voice=v2/en_speaker_1' -o test.wav"
echo ""
echo "3. Generate audio for questions in OpenCCB:"
echo " POST /question-bank/{id}/generate-audio"
echo ""
-189
View File
@@ -1,189 +0,0 @@
#!/bin/bash
# Fix Bark PyTorch 2.6+ compatibility issue
# Run this on t-800
set -e
echo "=== Fixing Bark PyTorch 2.6+ Compatibility ==="
echo ""
BARK_DIR="/opt/bark/bark"
# Backup original generation.py
echo "[1/3] Backing up original generation.py..."
cp $BARK_DIR/bark/generation.py $BARK_DIR/bark/generation.py.backup
# Patch generation.py to use weights_only=False
echo "[2/3] Patching generation.py..."
sed -i 's/torch.load(ckpt_path, map_location=device)/torch.load(ckpt_path, map_location=device, weights_only=False)/g' $BARK_DIR/bark/generation.py
# Create fixed bark_api.py
echo "[3/3] Creating fixed bark_api.py..."
cat > $BARK_DIR/bark/bark_api.py << 'PYEOF'
"""
Bark TTS API Server - Fixed for PyTorch 2.6+
Simple FastAPI wrapper for Bark text-to-speech
"""
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import StreamingResponse
from bark import SAMPLE_RATE, generate_audio, preload_models
from scipy.io.wavfile import write as write_wav
import numpy as np
import io
import torch
# Fix PyTorch 2.6+ weights_only issue
# This must be done BEFORE preload_models()
print("Configuring PyTorch for Bark compatibility...")
app = FastAPI(
title="Bark TTS API",
description="Text-to-Speech API using Suno AI's Bark",
version="1.0.0"
)
# Preload models on startup (with warm-up)
@app.on_event("startup")
async def startup_event():
print("Preloading Bark models...")
try:
preload_models()
print("Models loaded successfully!")
# Warm-up with a short generation
print("Warming up models with short generation...")
from bark import generate_text_semantic
text_semantic = generate_text_semantic("Hi", temp=0.7)
print("Warm-up complete! API ready.")
except Exception as e:
print(f"ERROR loading models: {e}")
raise
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "bark-tts"}
@app.get("/api/voices")
async def list_voices():
"""List available voice presets"""
return {
"voices": [
{"id": "v2/en_speaker_0", "name": "English Speaker 0", "language": "en"},
{"id": "v2/en_speaker_1", "name": "English Speaker 1", "language": "en"},
{"id": "v2/en_speaker_6", "name": "English Speaker 6", "language": "en"},
{"id": "v2/es_speaker_0", "name": "Spanish Speaker 0", "language": "es"},
{"id": "v2/es_speaker_1", "name": "Spanish Speaker 1", "language": "es"},
{"id": "v2/es_speaker_3", "name": "Spanish Speaker 3", "language": "es"},
]
}
@app.post("/api/generate")
async def generate_speech(
text: str = Query(..., min_length=1, max_length=500, description="Text to convert to speech"),
voice: str = Query(default="v2/en_speaker_1", description="Voice preset to use"),
speed: float = Query(default=1.0, ge=0.5, le=2.0, description="Speech speed multiplier"),
output_format: str = Query(default="wav", regex="^(mp3|wav|ogg)$", description="Output audio format")
):
"""Generate speech from text using Bark TTS"""
try:
# Generate audio
audio_array = generate_audio(text, history_prompt=voice)
# Apply speed adjustment if needed
if speed != 1.0:
new_length = int(len(audio_array) / speed)
audio_array = audio_array[:new_length]
# Convert to bytes
audio_buffer = io.BytesIO()
write_wav(audio_buffer, SAMPLE_RATE, audio_array)
audio_buffer.seek(0)
return StreamingResponse(
audio_buffer,
media_type="audio/wav",
headers={
"Content-Disposition": f"attachment; filename=speech.wav",
"X-Voice-Used": voice,
"X-Speed": str(speed),
"X-Duration-Seconds": str(len(audio_array) / SAMPLE_RATE)
}
)
except Exception as e:
print(f"Generation error: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/generate/batch")
async def generate_batch_speech(
texts: list[str] = Query(..., description="List of texts to convert"),
voice: str = Query(default="v2/en_speaker_1", description="Voice preset"),
speed: float = Query(default=1.0, description="Speech speed")
):
"""Generate multiple audio files in batch"""
results = []
for i, text in enumerate(texts):
try:
audio_array = generate_audio(text, history_prompt=voice)
# Save to temp file
import tempfile
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
write_wav(f.name, SAMPLE_RATE, audio_array)
results.append({
"index": i,
"text": text,
"duration_seconds": len(audio_array) / SAMPLE_RATE,
"status": "success"
})
except Exception as e:
results.append({
"index": i,
"text": text,
"error": str(e),
"status": "failed"
})
return {"results": results}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
PYEOF
# Fix ownership
chown bark:bark $BARK_DIR/bark/generation.py
chown bark:bark $BARK_DIR/bark/bark_api.py
echo ""
echo "=== Patch Applied ==="
echo ""
echo "Restarting Bark service..."
systemctl restart bark-tts
echo ""
echo "Waiting for models to load (this takes 1-2 minutes)..."
sleep 30
echo ""
echo "Checking service status..."
systemctl status bark-tts --no-pager
echo ""
echo "Testing API..."
if curl -s http://localhost:8443/health | jq . > /dev/null 2>&1; then
echo "✅ Bark API is running!"
curl -s http://localhost:8443/health | jq .
else
echo "⚠️ API is still loading models..."
echo "Check logs with: journalctl -u bark-tts -f"
fi
echo ""
echo "=== Fix Complete ==="
echo ""
echo "If you see errors, check:"
echo " 1. journalctl -u bark-tts -f"
echo " 2. systemctl status bark-tts"
echo ""
-208
View File
@@ -1,208 +0,0 @@
#!/bin/bash
# Manual Bark TTS Installation for t-800
# Run this ONCE on t-800 server
set -e
echo "=========================================="
echo " Manual Bark TTS Installation"
echo "=========================================="
echo ""
# Check if running as root or with sudo
if [ "$EUID" -ne 0 ]; then
echo "Please run with: sudo ./install_bark_manual.sh"
exit 1
fi
echo "[1/6] Installing system dependencies..."
apt-get update
apt-get install -y python3 python3-pip python3-venv git ffmpeg curl jq
echo ""
echo "[2/6] Creating bark user..."
if ! id -u bark > /dev/null 2>&1; then
useradd -r -m -s /bin/bash bark
echo "User 'bark' created"
else
echo "User 'bark' already exists"
fi
echo ""
echo "[3/6] Setting up application directory..."
BARK_DIR="/opt/bark"
mkdir -p $BARK_DIR
chown bark:bark $BARK_DIR
echo ""
echo "[4/6] Cloning Bark repository..."
cd $BARK_DIR
su - bark -c "cd $BARK_DIR && git clone https://github.com/suno-ai/bark.git"
chown -R bark:bark $BARK_DIR/bark
echo ""
echo "[5/6] Creating Python virtual environment and installing dependencies..."
cd $BARK_DIR/bark
su - bark -c "cd $BARK_DIR/bark && python3 -m venv venv"
su - bark -c "cd $BARK_DIR/bark && source venv/bin/activate && pip install --upgrade pip"
su - bark -c "cd $BARK_DIR/bark && source venv/bin/activate && pip install -e ."
su - bark -c "cd $BARK_DIR/bark && source venv/bin/activate && pip install fastapi uvicorn[standard] python-multipart numpy scipy"
echo ""
echo "[6/6] Creating systemd service..."
cat > /etc/systemd/system/bark-tts.service << EOF
[Unit]
Description=Bark TTS API Server
After=network.target
[Service]
Type=simple
User=bark
Group=bark
WorkingDirectory=$BARK_DIR/bark
Environment="PATH=$BARK_DIR/bark/venv/bin"
ExecStart=$BARK_DIR/bark/venv/bin/uvicorn bark_api:app --host 0.0.0.0 --port 8443 --workers 1
Restart=always
RestartSec=10
# Memory limits
MemoryMax=4G
MemoryHigh=3G
# CPU limits
CPUQuota=80%
[Install]
WantedBy=multi-user.target
EOF
# Create Bark API wrapper
cat > $BARK_DIR/bark/bark_api.py << 'PYEOF'
"""
Bark TTS API Server
Simple FastAPI wrapper for Bark text-to-speech
"""
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import StreamingResponse
from bark import SAMPLE_RATE, generate_audio, preload_models
from scipy.io.wavfile import write as write_wav
import numpy as np
import io
app = FastAPI(
title="Bark TTS API",
description="Text-to-Speech API using Suno AI's Bark",
version="1.0.0"
)
# Preload models on startup
print("Preloading Bark models...")
preload_models()
print("Models loaded!")
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "bark-tts"}
@app.get("/api/voices")
async def list_voices():
"""List available voice presets"""
return {
"voices": [
{"id": "v2/en_speaker_0", "name": "English Speaker 0", "language": "en"},
{"id": "v2/en_speaker_1", "name": "English Speaker 1", "language": "en"},
{"id": "v2/en_speaker_6", "name": "English Speaker 6", "language": "en"},
{"id": "v2/es_speaker_0", "name": "Spanish Speaker 0", "language": "es"},
{"id": "v2/es_speaker_1", "name": "Spanish Speaker 1", "language": "es"},
{"id": "v2/es_speaker_3", "name": "Spanish Speaker 3", "language": "es"},
]
}
@app.post("/api/generate")
async def generate_speech(
text: str = Query(..., min_length=1, max_length=500, description="Text to convert to speech"),
voice: str = Query(default="v2/en_speaker_1", description="Voice preset to use"),
speed: float = Query(default=1.0, ge=0.5, le=2.0, description="Speech speed multiplier"),
output_format: str = Query(default="wav", regex="^(mp3|wav|ogg)$", description="Output audio format")
):
"""Generate speech from text using Bark TTS"""
try:
# Generate audio
audio_array = generate_audio(text, history_prompt=voice)
# Apply speed adjustment if needed
if speed != 1.0:
new_length = int(len(audio_array) / speed)
audio_array = audio_array[:new_length]
# Convert to bytes
audio_buffer = io.BytesIO()
write_wav(audio_buffer, SAMPLE_RATE, audio_array)
audio_buffer.seek(0)
return StreamingResponse(
audio_buffer,
media_type="audio/wav",
headers={
"Content-Disposition": f"attachment; filename=speech.wav",
"X-Voice-Used": voice,
"X-Speed": str(speed),
"X-Duration-Seconds": str(len(audio_array) / SAMPLE_RATE)
}
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
PYEOF
chown bark:bark $BARK_DIR/bark/bark_api.py
echo ""
echo "Enabling and starting service..."
systemctl daemon-reload
systemctl enable bark-tts
systemctl start bark-tts
echo ""
echo "=========================================="
echo " Installation Complete!"
echo "=========================================="
echo ""
echo "Service Status:"
systemctl status bark-tts --no-pager
echo ""
echo "Waiting for Bark to preload models (this takes 1-2 minutes)..."
sleep 30
echo ""
echo "Testing API..."
if curl -s http://localhost:8000/health | jq . > /dev/null 2>&1; then
echo "✅ Bark API is running!"
curl -s http://localhost:8000/health | jq .
else
echo "⚠️ API is starting up, models are loading..."
echo "Check status with: systemctl status bark-tts"
echo "View logs with: journalctl -u bark-tts -f"
fi
echo ""
echo "=========================================="
echo " Next Steps"
echo "=========================================="
echo ""
echo "1. Test the API:"
echo " curl 'http://localhost:8000/api/generate?text=Hello%20World&voice=v2/en_speaker_1' -o test.wav"
echo ""
echo "2. Check service status anytime:"
echo " systemctl status bark-tts"
echo ""
echo "3. View logs:"
echo " journalctl -u bark-tts -f"
echo ""
echo "4. Restart service if needed:"
echo " systemctl restart bark-tts"
echo ""
-266
View File
@@ -1,266 +0,0 @@
#!/bin/bash
# Bark TTS Installation Script for t-800 server
# This script installs Suno AI's Bark text-to-speech system
set -e
echo "=========================================="
echo " Bark TTS Installation - Server t-800"
echo "=========================================="
# Check if running as root
if [ "$EUID" -ne 0 ]; then
echo "Please run as root (sudo ./install_bark.sh)"
exit 1
fi
# System requirements check
echo "[1/8] Checking system requirements..."
REQUIRED_RAM=8
AVAILABLE_RAM=$(free -g | awk '/^Mem:/{print $2}')
if [ $AVAILABLE_RAM -lt $REQUIRED_RAM ]; then
echo "WARNING: Bark requires at least ${REQUIRED_RAM}GB RAM (found: ${AVAILABLE_RAM}GB)"
echo "Continuing anyway, but performance may be poor..."
fi
# Update system packages
echo "[2/8] Updating system packages..."
apt-get update
apt-get install -y python3 python3-pip python3-venv git ffmpeg curl
# Create bark user
echo "[3/8] Creating bark user..."
if ! id -u bark > /dev/null 2>&1; then
useradd -r -m -s /bin/bash bark
echo "User 'bark' created"
else
echo "User 'bark' already exists"
fi
# Create application directory
echo "[4/8] Setting up application directory..."
BARK_DIR="/opt/bark"
mkdir -p $BARK_DIR
chown bark:bark $BARK_DIR
# Clone Bark repository
echo "[5/8] Cloning Bark repository..."
cd $BARK_DIR
if [ ! -d "bark" ]; then
su - bark -c "cd $BARK_DIR && git clone https://github.com/suno-ai/bark.git"
chown -R bark:bark $BARK_DIR/bark
else
echo "Bark repository already exists, updating..."
su - bark -c "cd $BARK_DIR/bark && git pull"
fi
# Create virtual environment
echo "[6/8] Creating Python virtual environment..."
cd $BARK_DIR/bark
su - bark -c "cd $BARK_DIR/bark && python3 -m venv venv"
# Install dependencies
echo "[7/8] Installing Python dependencies..."
su - bark -c "cd $BARK_DIR/bark && source venv/bin/activate && pip install --upgrade pip && pip install -e ."
# Additional dependencies for API server
su - bark -c "source $BARK_DIR/bark/venv/bin/activate && pip install fastapi uvicorn[standard] python-multipart numpy scipy"
# Create systemd service
echo "[8/8] Creating systemd service..."
cat > /etc/systemd/system/bark-tts.service << EOF
[Unit]
Description=Bark TTS API Server
After=network.target
[Service]
Type=simple
User=bark
Group=bark
WorkingDirectory=$BARK_DIR/bark
Environment="PATH=$BARK_DIR/bark/venv/bin"
ExecStart=$BARK_DIR/bark/venv/bin/uvicorn bark_api:app --host 0.0.0.0 --port 8000 --workers 1
Restart=always
RestartSec=10
# Memory limits
MemoryMax=4G
MemoryHigh=3G
# CPU limits
CPUQuota=80%
[Install]
WantedBy=multi-user.target
EOF
# Create Bark API wrapper
cat > $BARK_DIR/bark/bark_api.py << 'PYEOF'
"""
Bark TTS API Server
Simple FastAPI wrapper for Bark text-to-speech
"""
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import StreamingResponse, JSONResponse
from bark import SAMPLE_RATE, generate_audio, preload_models
from scipy.io.wavfile import write as write_wav
import numpy as np
import io
import os
import tempfile
app = FastAPI(
title="Bark TTS API",
description="Text-to-Speech API using Suno AI's Bark",
version="1.0.0"
)
# Preload models on startup
print("Preloading Bark models...")
preload_models()
print("Models loaded!")
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "bark-tts"}
@app.get("/api/voices")
async def list_voices():
"""List available voice presets"""
return {
"voices": [
{"id": "v2/en_speaker_0", "name": "English Speaker 0", "language": "en"},
{"id": "v2/en_speaker_1", "name": "English Speaker 1", "language": "en"},
{"id": "v2/en_speaker_2", "name": "English Speaker 2", "language": "en"},
{"id": "v2/en_speaker_3", "name": "English Speaker 3", "language": "en"},
{"id": "v2/en_speaker_4", "name": "English Speaker 4", "language": "en"},
{"id": "v2/en_speaker_5", "name": "English Speaker 5", "language": "en"},
{"id": "v2/en_speaker_6", "name": "English Speaker 6", "language": "en"},
{"id": "v2/en_speaker_7", "name": "English Speaker 7", "language": "en"},
{"id": "v2/en_speaker_8", "name": "English Speaker 8", "language": "en"},
{"id": "v2/en_speaker_9", "name": "English Speaker 9", "language": "en"},
{"id": "v2/es_speaker_0", "name": "Spanish Speaker 0", "language": "es"},
{"id": "v2/es_speaker_1", "name": "Spanish Speaker 1", "language": "es"},
{"id": "v2/es_speaker_2", "name": "Spanish Speaker 2", "language": "es"},
{"id": "v2/es_speaker_3", "name": "Spanish Speaker 3", "language": "es"},
{"id": "v2/es_speaker_4", "name": "Spanish Speaker 4", "language": "es"},
{"id": "v2/es_speaker_5", "name": "Spanish Speaker 5", "language": "es"},
{"id": "v2/es_speaker_6", "name": "Spanish Speaker 6", "language": "es"},
{"id": "v2/es_speaker_7", "name": "Spanish Speaker 7", "language": "es"},
{"id": "v2/es_speaker_8", "name": "Spanish Speaker 8", "language": "es"},
{"id": "v2/es_speaker_9", "name": "Spanish Speaker 9", "language": "es"},
]
}
@app.post("/api/generate")
async def generate_speech(
text: str = Query(..., min_length=1, max_length=500, description="Text to convert to speech"),
voice: str = Query(default="v2/en_speaker_1", description="Voice preset to use"),
speed: float = Query(default=1.0, ge=0.5, le=2.0, description="Speech speed multiplier"),
output_format: str = Query(default="mp3", regex="^(mp3|wav|ogg)$", description="Output audio format")
):
"""Generate speech from text using Bark TTS"""
try:
# Extract speaker number from voice preset
parts = voice.split("_")
if len(parts) >= 3:
speaker = f"{parts[0]}_{parts[1]}_{parts[2]}"
else:
speaker = "v2/en_speaker_1"
# Generate audio
audio_array = generate_audio(text, history_prompt=speaker)
# Apply speed adjustment if needed
if speed != 1.0:
# Simple speed adjustment by resampling
new_length = int(len(audio_array) / speed)
audio_array = audio_array[:new_length]
# Convert to bytes
audio_buffer = io.BytesIO()
write_wav(audio_buffer, SAMPLE_RATE, audio_array)
audio_buffer.seek(0)
# For MP3 output, we'd need to add pydub/ffmpeg
# For now, return WAV
media_type = "audio/wav"
filename = f"speech_{voice}.{output_format}"
return StreamingResponse(
audio_buffer,
media_type=media_type,
headers={
"Content-Disposition": f"attachment; filename={filename}",
"X-Voice-Used": voice,
"X-Speed": str(speed),
"X-Duration-Seconds": str(len(audio_array) / SAMPLE_RATE)
}
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/generate/batch")
async def generate_batch_speech(
texts: list[str] = Query(..., description="List of texts to convert"),
voice: str = Query(default="v2/en_speaker_1", description="Voice preset"),
speed: float = Query(default=1.0, description="Speech speed")
):
"""Generate multiple audio files in batch"""
results = []
for i, text in enumerate(texts):
try:
audio_array = generate_audio(text, history_prompt=voice)
# Save to temp file
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as f:
write_wav(f.name, SAMPLE_RATE, audio_array)
results.append({
"index": i,
"text": text,
"duration_seconds": len(audio_array) / SAMPLE_RATE,
"status": "success"
})
except Exception as e:
results.append({
"index": i,
"text": text,
"error": str(e),
"status": "failed"
})
return JSONResponse(content={"results": results})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
PYEOF
chown bark:bark $BARK_DIR/bark/bark_api.py
# Enable and start service
systemctl daemon-reload
systemctl enable bark-tts
systemctl start bark-tts
echo ""
echo "=========================================="
echo " Installation Complete!"
echo "=========================================="
echo ""
echo "Service Status:"
systemctl status bark-tts --no-pager
echo ""
echo "API Endpoints:"
echo " - Health: http://localhost:8000/health"
echo " - Voices: http://localhost:8000/api/voices"
echo " - Generate: http://localhost:8000/api/generate?text=Hello&voice=v2/en_speaker_1"
echo ""
echo "Usage Example:"
echo " curl 'http://localhost:8000/api/generate?text=What%20color%20is%20the%20sky%3F&voice=v2/en_speaker_1' -o question.wav"
echo ""
echo "Logs: journalctl -u bark-tts -f"
echo ""