Spaces:
Running
Running
File size: 11,762 Bytes
0a1c5fe 2fcb053 0a1c5fe 785a835 0a1c5fe f964d49 0a1c5fe 2fcb053 f964d49 0a1c5fe 2fcb053 0a1c5fe 785a835 0a1c5fe 785a835 0a1c5fe 2fcb053 785a835 0a1c5fe 785a835 2fcb053 785a835 2fcb053 785a835 2fcb053 785a835 0a1c5fe 785a835 0a1c5fe 2fcb053 785a835 0a1c5fe 785a835 0a1c5fe 785a835 0a1c5fe 785a835 0a1c5fe 785a835 0a1c5fe 2fcb053 f964d49 785a835 f964d49 785a835 f964d49 785a835 0a1c5fe 785a835 0a1c5fe 785a835 0a1c5fe f964d49 0a1c5fe 785a835 0a1c5fe 785a835 0a1c5fe 2fcb053 0a1c5fe 785a835 0a1c5fe 785a835 0a1c5fe 2fcb053 0a1c5fe 2fcb053 0a1c5fe 2fcb053 0a1c5fe 2fcb053 0a1c5fe 2fcb053 0a1c5fe 2fcb053 0a1c5fe f964d49 | 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 | """
ClearWave AI β API Space (FastAPI)
===================================
Endpoints: /api/health | /api/process-url
Pipeline:
1. Download audio from URL
2. Denoise / enhance β Denoiser (Cleanvoice SDK)
3. Transcribe β Groq Whisper large-v3 (primary) / faster-whisper (fallback)
4. Translate β NLLB-200-1.3B (primary) / Google Translate (fallback)
5. Summarize β Extractive (position-scored)
6. Upload result β Cloudinary
All secrets read from HF Space environment variables:
CLEANVOICE_API_KEY, CLOUD_NAME, API_KEY, API_SECRET, GROQ_API_KEY
"""
import os
import json
import time
import tempfile
import logging
import requests
import cloudinary
import cloudinary.uploader
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from denoiser import Denoiser
from transcriber import Transcriber
from translator import Translator
# ββ Cloudinary config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
cloudinary.config(
cloud_name = os.environ.get("CLOUD_NAME"),
api_key = os.environ.get("API_KEY"),
api_secret = os.environ.get("API_SECRET"),
)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ββ Singleton instances (loaded once at startup) βββββββββββββββββββββββββββββββ
denoiser = Denoiser()
transcriber = Transcriber()
translator = Translator()
app = FastAPI(title="ClearWave AI API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PIPELINE
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_pipeline(audio_path, src_lang="auto", tgt_lang="te",
opt_fillers=True, opt_stutters=True, opt_silences=True,
opt_breaths=True, opt_mouth=True):
"""
Generator β yields SSE-style dicts at each step.
Caller wraps each dict in "data: <json>\n\n"
"""
out_dir = tempfile.mkdtemp()
stats = {}
word_segs = []
try:
# ββ Step 1: Cleanvoice β full audio enhancement βββββββββββββββββββββββ
yield {"status": "processing", "step": 1,
"message": "Step 1/4 β Enhancing audio with Cleanvoice..."}
try:
result = denoiser.process(
audio_path, out_dir,
fillers=opt_fillers,
stutters=opt_stutters,
long_silences=opt_silences,
breaths=opt_breaths,
mouth_sounds=opt_mouth,
)
clean1 = result["audio_path"]
stats = {
"noise_method": "Cleanvoice API",
"fillers_removed": "yes" if opt_fillers else "no",
"stutters_removed": "yes" if opt_stutters else "no",
"silences_removed_sec": "yes" if opt_silences else "no",
"breaths_reduced": opt_breaths,
"mouth_sounds_removed": "yes" if opt_mouth else "no",
}
logger.info("[Pipeline] Cleanvoice enhancement complete")
except Exception as e:
# Cleanvoice failed β log it and continue with original audio
logger.error(f"[Pipeline] Cleanvoice failed: {e} β using original audio")
clean1 = audio_path
stats = {
"noise_method": f"Cleanvoice failed: {e}",
"fillers_removed": 0,
"stutters_removed": 0,
"silences_removed_sec": 0,
"breaths_reduced": False,
"mouth_sounds_removed": 0,
}
# ββ Step 2: Transcribe ββββββββββββββββββββββββββββββββββββββββββββββββ
yield {"status": "processing", "step": 2,
"message": "Step 2/4 β Transcribing..."}
transcript, detected_lang, t_method = transcriber.transcribe(clean1, src_lang)
word_segs = transcriber._last_segments
# Clean filler words from transcript text too
if opt_fillers:
transcript = denoiser.clean_transcript_fillers(transcript)
logger.info(f"[Pipeline] Transcription done: {len(transcript.split())} words, lang={detected_lang}")
# ββ Step 3: Translate βββββββββββββββββββββββββββββββββββββββββββββββββ
translation = transcript
tl_method = "same language"
if tgt_lang != "auto" and detected_lang != tgt_lang:
yield {"status": "processing", "step": 3,
"message": "Step 3/4 β Translating..."}
translation, tl_method = translator.translate(transcript, detected_lang, tgt_lang)
logger.info(f"[Pipeline] Translation done via {tl_method}")
else:
yield {"status": "processing", "step": 3,
"message": "Step 3/4 β Skipping translation (same language)..."}
# ββ Step 4: Summarize + upload to Cloudinary ββββββββββββββββββββββββββ
yield {"status": "processing", "step": 4,
"message": "Step 4/4 β Summarizing & uploading..."}
summary = translator.summarize(transcript)
enhanced_url = None
try:
upload_result = cloudinary.uploader.upload(
clean1,
resource_type="video", # Cloudinary uses "video" for audio files
folder="clearwave_enhanced",
)
enhanced_url = upload_result["secure_url"]
logger.info(f"[Pipeline] Cloudinary upload done: {enhanced_url}")
except Exception as e:
logger.error(f"[Pipeline] Cloudinary upload failed: {e}")
# ββ Done ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
yield {
"status": "done",
"step": 4,
"message": "Done!",
"transcript": transcript,
"translation": translation,
"summary": summary,
"enhancedAudio": enhanced_url,
"stats": {
"language": detected_lang.upper(),
"noise_method": stats.get("noise_method", "Cleanvoice API"),
"fillers_removed": stats.get("fillers_removed", 0),
"stutters_removed": stats.get("stutters_removed", 0),
"silences_removed_sec": stats.get("silences_removed_sec", 0),
"breaths_reduced": stats.get("breaths_reduced", False),
"mouth_sounds_removed": stats.get("mouth_sounds_removed", 0),
"transcription_method": t_method,
"translation_method": tl_method,
"word_segments": len(word_segs),
"transcript_words": len(transcript.split()),
},
}
except Exception as e:
logger.error(f"[Pipeline] Fatal error: {e}", exc_info=True)
yield {"status": "error", "message": f"Error: {str(e)}"}
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# ROUTES
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/api/health")
async def health():
return JSONResponse({"status": "ok", "service": "ClearWave AI API"})
@app.post("/api/process-url")
async def process_url(request: Request):
data = await request.json()
audio_url = data.get("audioUrl")
audio_id = data.get("audioId", "")
src_lang = data.get("srcLang", "auto")
tgt_lang = data.get("tgtLang", "te")
opt_fillers = data.get("optFillers", True)
opt_stutters = data.get("optStutters", True)
opt_silences = data.get("optSilences", True)
opt_breaths = data.get("optBreaths", True)
opt_mouth = data.get("optMouth", True)
if not audio_url:
return JSONResponse({"error": "audioUrl is required"}, status_code=400)
async def generate():
import sys
def sse(obj):
sys.stdout.flush()
return "data: " + json.dumps(obj) + "\n\n"
yield sse({"status": "processing", "step": 0, "message": "Downloading audio..."})
# ββ Download audio from URL βββββββββββββββββββββββββββββββββββββββββββ
try:
resp = requests.get(audio_url, timeout=60, stream=True)
resp.raise_for_status()
# Detect extension β support WhatsApp .opus and common formats
lower_url = audio_url.lower().split("?")[0]
if ".opus" in lower_url: suffix = ".opus"
elif ".ogg" in lower_url: suffix = ".ogg"
elif ".aac" in lower_url: suffix = ".aac"
elif ".m4a" in lower_url: suffix = ".m4a"
elif ".wav" in lower_url: suffix = ".wav"
else: suffix = ".mp3"
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
downloaded = 0
total = int(resp.headers.get("content-length", 0))
for chunk in resp.iter_content(chunk_size=65536):
if chunk:
tmp.write(chunk)
downloaded += len(chunk)
if total:
pct = int(downloaded * 100 / total)
yield sse({"status": "processing", "step": 0,
"message": f"Downloading... {pct}%"})
tmp.close()
except Exception as e:
yield sse({"status": "error", "message": f"Download failed: {e}"})
return
# ββ Run pipeline ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
for result in run_pipeline(tmp.name, src_lang, tgt_lang,
opt_fillers, opt_stutters, opt_silences,
opt_breaths, opt_mouth):
result["audioId"] = audio_id
yield sse(result)
try:
os.unlink(tmp.name)
except Exception:
pass
return StreamingResponse(
generate(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
) |