File size: 29,166 Bytes
475b0b9 224556e 1936ef7 224556e 1936ef7 7a61b58 1936ef7 7a61b58 1936ef7 7a61b58 1936ef7 7a61b58 1936ef7 6efcad4 1936ef7 6efcad4 0a0efec 6efcad4 0a0efec 6efcad4 1936ef7 6efcad4 1936ef7 6efcad4 f25cff8 1936ef7 f25cff8 1936ef7 6efcad4 0a0efec 6efcad4 0a0efec 6efcad4 7a61b58 1936ef7 475b0b9 665c478 475b0b9 1936ef7 224556e 1936ef7 224556e 94b0142 224556e 7222675 224556e 1936ef7 224556e 1936ef7 224556e 1936ef7 224556e 1936ef7 224556e 1936ef7 224556e 1936ef7 224556e 1936ef7 224556e 1936ef7 224556e 1936ef7 224556e 1936ef7 0a0efec 1936ef7 224556e 94b0142 475b0b9 1936ef7 475b0b9 1936ef7 224556e 1936ef7 0a0efec 1936ef7 0a0efec 1936ef7 0a0efec 1936ef7 224556e 475b0b9 224556e 475b0b9 224556e 475b0b9 1936ef7 475b0b9 224556e 475b0b9 1936ef7 475b0b9 ef20fe6 475b0b9 224556e 475b0b9 224556e 475b0b9 224556e 475b0b9 94b0142 475b0b9 94b0142 224556e 475b0b9 abca105 475b0b9 abca105 475b0b9 94b0142 224556e 475b0b9 abca105 475b0b9 224556e 94b0142 224556e 475b0b9 94b0142 475b0b9 94b0142 224556e 475b0b9 94b0142 475b0b9 224556e 475b0b9 224556e 94b0142 224556e 475b0b9 94b0142 475b0b9 94b0142 475b0b9 94b0142 224556e 475b0b9 94b0142 475b0b9 94b0142 224556e 475b0b9 94b0142 224556e 475b0b9 94b0142 224556e 94b0142 224556e 475b0b9 94b0142 475b0b9 e5a6062 1936ef7 ef20fe6 1936ef7 ef20fe6 1936ef7 f238ccb 1936ef7 f238ccb 0a0efec f238ccb 1936ef7 ef20fe6 f238ccb 1936ef7 f238ccb 843c466 1936ef7 f238ccb 94b0142 1936ef7 94b0142 1936ef7 475b0b9 1936ef7 475b0b9 f238ccb 1936ef7 f238ccb |
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 |
import argparse
import io
import os
from time import time
from typing import List
import tempfile
import uvicorn
from fastapi import Depends, FastAPI, File, HTTPException, Query, Request, UploadFile, Body, Form
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse, StreamingResponse
from PIL import Image
from pydantic import BaseModel, field_validator
from pydantic_settings import BaseSettings
from slowapi import Limiter
from slowapi.util import get_remote_address
import torch
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, AutoModel
from IndicTransToolkit import IndicProcessor
import json
import asyncio
from contextlib import asynccontextmanager
import soundfile as sf
import numpy as np
import requests
from starlette.responses import StreamingResponse
from logging_config import logger
from tts_config import SPEED, ResponseFormat, config as tts_config
from gemma_llm import LLMManager # Assuming this is your custom LLMManager
# Device setup
if torch.cuda.is_available():
device = "cuda:0"
logger.info("GPU will be used for inference")
else:
device = "cpu"
logger.info("CPU will be used for inference")
torch_dtype = torch.bfloat16 if device != "cpu" else torch.float32
# Check CUDA availability and version
cuda_available = torch.cuda.is_available()
cuda_version = torch.version.cuda if cuda_available else None
if torch.cuda.is_available():
device_idx = torch.cuda.current_device()
capability = torch.cuda.get_device_capability(device_idx)
compute_capability_float = float(f"{capability[0]}.{capability[1]}")
print(f"CUDA version: {cuda_version}")
print(f"CUDA Compute Capability: {compute_capability_float}")
else:
print("CUDA is not available on this system.")
# Settings
class Settings(BaseSettings):
llm_model_name: str = "google/gemma-3-4b-it"
max_tokens: int = 512
host: str = "0.0.0.0"
port: int = 7860
chat_rate_limit: str = "100/minute"
speech_rate_limit: str = "5/minute"
@field_validator("chat_rate_limit", "speech_rate_limit")
def validate_rate_limit(cls, v):
if not v.count("/") == 1 or not v.split("/")[0].isdigit():
raise ValueError("Rate limit must be in format 'number/period' (e.g., '5/minute')")
return v
class Config:
env_file = ".env"
settings = Settings()
# TTS Manager
class TTSManager:
def __init__(self, device_type=device):
self.device_type = device_type
self.model = None
self.repo_id = "ai4bharat/IndicF5"
async def load(self):
logger.info("Loading TTS model IndicF5...")
self.model = await asyncio.to_thread(
AutoModel.from_pretrained,
self.repo_id,
trust_remote_code=True
)
self.model = self.model.to(self.device_type)
logger.info("TTS model IndicF5 loaded")
def synthesize(self, text, ref_audio_path, ref_text):
if not self.model:
raise ValueError("TTS model not loaded")
return self.model(text, ref_audio_path=ref_audio_path, ref_text=ref_text)
# TTS Constants
EXAMPLES = [
{
"audio_name": "KAN_F (Happy)",
"audio_url": "https://github.com/AI4Bharat/IndicF5/raw/refs/heads/main/prompts/KAN_F_HAPPY_00001.wav",
"ref_text": "ನಮ್ ಫ್ರಿಜ್ಜಲ್ಲಿ ಕೂಲಿಂಗ್ ಸಮಸ್ಯೆ ಆಗಿ ನಾನ್ ಭಾಳ ದಿನದಿಂದ ಒದ್ದಾಡ್ತಿದ್ದೆ, ಆದ್ರೆ ಅದ್ನೀಗ ಮೆಕಾನಿಕ್ ಆಗಿರೋ ನಿಮ್ ಸಹಾಯ್ದಿಂದ ಬಗೆಹರಿಸ್ಕೋಬೋದು ಅಂತಾಗಿ ನಿರಾಳ ಆಯ್ತು ನಂಗೆ.",
"synth_text": "ಚೆನ್ನೈನ ಶೇರ್ ಆಟೋ ಪ್ರಯಾಣಿಕರ ನಡುವೆ ಆಹಾರವನ್ನು ಹಂಚಿಕೊಂಡು ತಿನ್ನುವುದು ನನಗೆ ಮನಸ್ಸಿಗೆ ತುಂಬಾ ಒಳ್ಳೆಯದೆನಿಸುವ ವಿಷಯ."
},
]
# Pydantic models for TTS
class SynthesizeRequest(BaseModel):
text: str
ref_audio_name: str
ref_text: str = None
class KannadaSynthesizeRequest(BaseModel):
text: str
# TTS Functions
def load_audio_from_url(url: str):
response = requests.get(url)
if response.status_code == 200:
audio_data, sample_rate = sf.read(io.BytesIO(response.content))
return sample_rate, audio_data
raise HTTPException(status_code=500, detail="Failed to load reference audio from URL.")
def synthesize_speech(tts_manager: TTSManager, text: str, ref_audio_name: str, ref_text: str):
ref_audio_url = None
for example in EXAMPLES:
if example["audio_name"] == ref_audio_name:
ref_audio_url = example["audio_url"]
if not ref_text:
ref_text = example["ref_text"]
break
if not ref_audio_url:
raise HTTPException(status_code=400, detail="Invalid reference audio name.")
if not text.strip():
raise HTTPException(status_code=400, detail="Text to synthesize cannot be empty.")
if not ref_text or not ref_text.strip():
raise HTTPException(status_code=400, detail="Reference text cannot be empty.")
sample_rate, audio_data = load_audio_from_url(ref_audio_url)
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_audio:
sf.write(temp_audio.name, audio_data, samplerate=sample_rate, format='WAV')
temp_audio.flush()
audio = tts_manager.synthesize(text, ref_audio_path=temp_audio.name, ref_text=ref_text)
if audio.dtype == np.int16:
audio = audio.astype(np.float32) / 32768.0
buffer = io.BytesIO()
sf.write(buffer, audio, 24000, format='WAV')
buffer.seek(0)
return buffer
# Supported languages
SUPPORTED_LANGUAGES = {
"asm_Beng", "kas_Arab", "pan_Guru", "ben_Beng", "kas_Deva", "san_Deva",
"brx_Deva", "mai_Deva", "sat_Olck", "doi_Deva", "mal_Mlym", "snd_Arab",
"eng_Latn", "mar_Deva", "snd_Deva", "gom_Deva", "mni_Beng", "tam_Taml",
"guj_Gujr", "mni_Mtei", "tel_Telu", "hin_Deva", "npi_Deva", "urd_Arab",
"kan_Knda", "ory_Orya",
"deu_Latn", "fra_Latn", "nld_Latn", "spa_Latn", "ita_Latn",
"por_Latn", "rus_Cyrl", "pol_Latn"
}
# Translation Manager
class TranslateManager:
def __init__(self, src_lang, tgt_lang, device_type=device, use_distilled=True):
self.device_type = device_type
self.tokenizer, self.model = self.initialize_model(src_lang, tgt_lang, use_distilled)
def initialize_model(self, src_lang, tgt_lang, use_distilled):
if src_lang.startswith("eng") and not tgt_lang.startswith("eng"):
model_name = "ai4bharat/indictrans2-en-indic-dist-200M" if use_distilled else "ai4bharat/indictrans2-en-indic-1B"
elif not src_lang.startswith("eng") and tgt_lang.startswith("eng"):
model_name = "ai4bharat/indictrans2-indic-en-dist-200M" if use_distilled else "ai4bharat/indictrans2-indic-en-1B"
elif not src_lang.startswith("eng") and not tgt_lang.startswith("eng"):
model_name = "ai4bharat/indictrans2-indic-indic-dist-320M" if use_distilled else "ai4bharat/indictrans2-indic-indic-1B"
else:
raise ValueError("Invalid language combination: English to English translation is not supported.")
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model = AutoModelForSeq2SeqLM.from_pretrained(
model_name,
trust_remote_code=True,
torch_dtype=torch.float16,
attn_implementation="flash_attention_2"
).to(self.device_type)
model = torch.compile(model, mode="reduce-overhead")
print("Model compiled with torch.compile")
return tokenizer, model
class ModelManager:
def __init__(self, device_type=device, use_distilled=True, is_lazy_loading=False):
self.models = {}
self.device_type = device_type
self.use_distilled = use_distilled
self.is_lazy_loading = is_lazy_loading
async def load_model(self, src_lang, tgt_lang, key):
logger.info(f"Loading translation model for {src_lang} -> {tgt_lang}")
if src_lang.startswith("eng") and not tgt_lang.startswith("eng"):
model_name = "ai4bharat/indictrans2-en-indic-dist-200M" if self.use_distilled else "ai4bharat/indictrans2-en-indic-1B"
elif not src_lang.startswith("eng") and tgt_lang.startswith("eng"):
model_name = "ai4bharat/indictrans2-indic-en-dist-200M" if self.use_distilled else "ai4bharat/indictrans2-indic-en-1B"
else:
model_name = "ai4bharat/indictrans2-indic-indic-dist-320M" if self.use_distilled else "ai4bharat/indictrans2-indic-indic-1B"
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model = await asyncio.to_thread(
AutoModelForSeq2SeqLM.from_pretrained,
model_name,
trust_remote_code=True,
torch_dtype=torch.float16,
attn_implementation="flash_attention_2"
)
model = model.to(self.device_type)
model = torch.compile(model, mode="reduce-overhead")
self.models[key] = TranslateManager(src_lang, tgt_lang, self.device_type, self.use_distilled)
logger.info(f"Loaded translation model for {key}")
def get_model(self, src_lang, tgt_lang):
key = self._get_model_key(src_lang, tgt_lang)
if key not in self.models:
if self.is_lazy_loading:
asyncio.create_task(self.load_model(src_lang, tgt_lang, key))
else:
raise ValueError(f"Model for {key} is not preloaded and lazy loading is disabled.")
return self.models.get(key)
def _get_model_key(self, src_lang, tgt_lang):
if src_lang.startswith("eng") and not tgt_lang.startswith("eng"):
return 'eng_indic'
elif not src_lang.startswith("eng") and tgt_lang.startswith("eng"):
return 'indic_eng'
elif not src_lang.startswith("eng") and not tgt_lang.startswith("eng"):
return 'indic_indic'
raise ValueError("Invalid language combination")
# ASR Manager
class ASRModelManager:
def __init__(self, device_type="cuda"):
self.device_type = device_type
self.model = None
self.model_language = {"kannada": "kn"}
async def load(self):
logger.info("Loading ASR model...")
self.model = await asyncio.to_thread(
AutoModel.from_pretrained,
"ai4bharat/indic-conformer-600m-multilingual",
trust_remote_code=True
)
logger.info("ASR model loaded")
# Global Managers
llm_manager = LLMManager(settings.llm_model_name)
model_manager = ModelManager()
asr_manager = ASRModelManager()
tts_manager = TTSManager()
ip = IndicProcessor(inference=True)
# Pydantic Models
class ChatRequest(BaseModel):
prompt: str
src_lang: str = "kan_Knda"
tgt_lang: str = "kan_Knda"
@field_validator("prompt")
def prompt_must_be_valid(cls, v):
if len(v) > 1000:
raise ValueError("Prompt cannot exceed 1000 characters")
return v.strip()
@field_validator("src_lang", "tgt_lang")
def validate_language(cls, v):
if v not in SUPPORTED_LANGUAGES:
raise ValueError(f"Unsupported language code: {v}. Supported codes: {', '.join(SUPPORTED_LANGUAGES)}")
return v
class ChatResponse(BaseModel):
response: str
class TranslationRequest(BaseModel):
sentences: List[str]
src_lang: str
tgt_lang: str
class TranslationResponse(BaseModel):
translations: List[str]
class TranscriptionResponse(BaseModel):
text: str
# Dependency
def get_translate_manager(src_lang: str, tgt_lang: str) -> TranslateManager:
return model_manager.get_model(src_lang, tgt_lang)
# Lifespan Event Handler
@asynccontextmanager
async def lifespan(app: FastAPI):
async def load_all_models():
tasks = [
asyncio.create_task(llm_manager.load()),
asyncio.create_task(asr_manager.load()),
asyncio.create_task(tts_manager.load()),
asyncio.create_task(model_manager.load_model('eng_Latn', 'kan_Knda', 'eng_indic')),
asyncio.create_task(model_manager.load_model('kan_Knda', 'eng_Latn', 'indic_eng')),
asyncio.create_task(model_manager.load_model('kan_Knda', 'hin_Deva', 'indic_indic')),
]
await asyncio.gather(*tasks)
logger.info("All models loaded successfully")
logger.info("Starting model loading in background...")
asyncio.create_task(load_all_models())
yield
await llm_manager.unload()
logger.info("Server shutdown complete")
# FastAPI App
app = FastAPI(
title="Dhwani API",
description="AI Chat API supporting Indian languages",
version="1.0.0",
redirect_slashes=False,
lifespan=lifespan
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
# API Endpoints
@app.post("/audio/speech", response_class=StreamingResponse)
async def synthesize_kannada(request: KannadaSynthesizeRequest):
if not tts_manager.model:
raise HTTPException(status_code=503, detail="TTS model still loading, please try again later")
kannada_example = next(ex for ex in EXAMPLES if ex["audio_name"] == "KAN_F (Happy)")
if not request.text.strip():
raise HTTPException(status_code=400, detail="Text to synthesize cannot be empty.")
audio_buffer = synthesize_speech(
tts_manager,
text=request.text,
ref_audio_name="KAN_F (Happy)",
ref_text=kannada_example["ref_text"]
)
return StreamingResponse(
audio_buffer,
media_type="audio/wav",
headers={"Content-Disposition": "attachment; filename=synthesized_kannada_speech.wav"}
)
@app.post("/translate", response_model=TranslationResponse)
async def translate(request: TranslationRequest, translate_manager: TranslateManager = Depends(get_translate_manager)):
input_sentences = request.sentences
src_lang = request.src_lang
tgt_lang = request.tgt_lang
if not input_sentences:
raise HTTPException(status_code=400, detail="Input sentences are required")
batch = ip.preprocess_batch(input_sentences, src_lang=src_lang, tgt_lang=tgt_lang)
inputs = translate_manager.tokenizer(
batch,
truncation=True,
padding="longest",
return_tensors="pt",
return_attention_mask=True,
).to(translate_manager.device_type)
with torch.no_grad():
generated_tokens = translate_manager.model.generate(
**inputs,
use_cache=True,
min_length=0,
max_length=256,
num_beams=5,
num_return_sequences=1,
)
with translate_manager.tokenizer.as_target_tokenizer():
generated_tokens = translate_manager.tokenizer.batch_decode(
generated_tokens.detach().cpu().tolist(),
skip_special_tokens=True,
clean_up_tokenization_spaces=True,
)
translations = ip.postprocess_batch(generated_tokens, lang=tgt_lang)
return TranslationResponse(translations=translations)
async def perform_internal_translation(sentences: List[str], src_lang: str, tgt_lang: str) -> List[str]:
translate_manager = model_manager.get_model(src_lang, tgt_lang)
request = TranslationRequest(sentences=sentences, src_lang=src_lang, tgt_lang=tgt_lang)
response = await translate(request, translate_manager)
return response.translations
@app.get("/v1/health")
async def health_check():
return {"status": "healthy", "model": settings.llm_model_name}
@app.get("/")
async def home():
return RedirectResponse(url="/docs")
@app.post("/v1/unload_all_models")
async def unload_all_models():
try:
logger.info("Starting to unload all models...")
await llm_manager.unload()
logger.info("All models unloaded successfully")
return {"status": "success", "message": "All models unloaded"}
except Exception as e:
logger.error(f"Error unloading models: {str(e)}")
raise HTTPException(status_code=500, detail=f"Failed to unload models: {str(e)}")
@app.post("/v1/load_all_models")
async def load_all_models():
try:
logger.info("Starting to load all models...")
await llm_manager.load()
logger.info("All models loaded successfully")
return {"status": "success", "message": "All models loaded"}
except Exception as e:
logger.error(f"Error loading models: {str(e)}")
raise HTTPException(status_code=500, detail=f"Failed to unload models: {str(e)}")
@app.post("/v1/translate", response_model=TranslationResponse)
async def translate_endpoint(request: TranslationRequest):
logger.info(f"Received translation request: {request.dict()}")
try:
translations = await perform_internal_translation(
sentences=request.sentences,
src_lang=request.src_lang,
tgt_lang=request.tgt_lang
)
logger.info(f"Translation successful: {translations}")
return TranslationResponse(translations=translations)
except Exception as e:
logger.error(f"Unexpected error during translation: {str(e)}")
raise HTTPException(status_code=500, detail=f"Translation failed: {str(e)}")
@app.post("/v1/chat", response_model=ChatResponse)
@limiter.limit(settings.chat_rate_limit)
async def chat(request: Request, chat_request: ChatRequest):
if not chat_request.prompt:
raise HTTPException(status_code=400, detail="Prompt cannot be empty")
logger.info(f"Received prompt: {chat_request.prompt}, src_lang: {chat_request.src_lang}, tgt_lang: {chat_request.tgt_lang}")
EUROPEAN_LANGUAGES = {"deu_Latn", "fra_Latn", "nld_Latn", "spa_Latn", "ita_Latn", "por_Latn", "rus_Cyrl", "pol_Latn"}
try:
if chat_request.src_lang != "eng_Latn" and chat_request.src_lang not in EUROPEAN_LANGUAGES:
translated_prompt = await perform_internal_translation(
sentences=[chat_request.prompt],
src_lang=chat_request.src_lang,
tgt_lang="eng_Latn"
)
prompt_to_process = translated_prompt[0]
logger.info(f"Translated prompt to English: {prompt_to_process}")
else:
prompt_to_process = chat_request.prompt
logger.info("Prompt in English or European language, no translation needed")
response = await llm_manager.generate(prompt_to_process, settings.max_tokens)
logger.info(f"Generated response: {response}")
if chat_request.tgt_lang != "eng_Latn" and chat_request.tgt_lang not in EUROPEAN_LANGUAGES:
translated_response = await perform_internal_translation(
sentences=[response],
src_lang="eng_Latn",
tgt_lang=chat_request.tgt_lang
)
final_response = translated_response[0]
logger.info(f"Translated response to {chat_request.tgt_lang}: {final_response}")
else:
final_response = response
logger.info(f"Response in {chat_request.tgt_lang}, no translation needed")
return ChatResponse(response=final_response)
except Exception as e:
logger.error(f"Error processing request: {str(e)}")
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@app.post("/v1/visual_query/")
async def visual_query(
file: UploadFile = File(...),
query: str = Body(...),
src_lang: str = Query("kan_Knda", enum=list(SUPPORTED_LANGUAGES)),
tgt_lang: str = Query("kan_Knda", enum=list(SUPPORTED_LANGUAGES)),
):
try:
image = Image.open(file.file)
if image.size == (0, 0):
raise HTTPException(status_code=400, detail="Uploaded image is empty or invalid")
if src_lang != "eng_Latn":
translated_query = await perform_internal_translation(
sentences=[query],
src_lang=src_lang,
tgt_lang="eng_Latn"
)
query_to_process = translated_query[0]
logger.info(f"Translated query to English: {query_to_process}")
else:
query_to_process = query
logger.info("Query already in English, no translation needed")
answer = await llm_manager.vision_query(image, query_to_process)
logger.info(f"Generated English answer: {answer}")
if tgt_lang != "eng_Latn":
translated_answer = await perform_internal_translation(
sentences=[answer],
src_lang="eng_Latn",
tgt_lang=tgt_lang
)
final_answer = translated_answer[0]
logger.info(f"Translated answer to {tgt_lang}: {final_answer}")
else:
final_answer = answer
logger.info("Answer kept in English, no translation needed")
return {"answer": final_answer}
except Exception as e:
logger.error(f"Error processing request: {str(e)}")
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@app.post("/v1/chat_v2", response_model=ChatResponse)
@limiter.limit(settings.chat_rate_limit)
async def chat_v2(
request: Request,
prompt: str = Form(...),
image: UploadFile = File(default=None),
src_lang: str = Form("kan_Knda"),
tgt_lang: str = Form("kan_Knda"),
):
if not prompt:
raise HTTPException(status_code=400, detail="Prompt cannot be empty")
if src_lang not in SUPPORTED_LANGUAGES or tgt_lang not in SUPPORTED_LANGUAGES:
raise HTTPException(status_code=400, detail=f"Unsupported language code. Supported codes: {', '.join(SUPPORTED_LANGUAGES)}")
logger.info(f"Received prompt: {prompt}, src_lang: {src_lang}, tgt_lang: {tgt_lang}, Image provided: {image is not None}")
try:
if image:
image_data = await image.read()
if not image_data:
raise HTTPException(status_code=400, detail="Uploaded image is empty")
img = Image.open(io.BytesIO(image_data))
if src_lang != "eng_Latn":
translated_prompt = await perform_internal_translation(
sentences=[prompt],
src_lang=src_lang,
tgt_lang="eng_Latn"
)
prompt_to_process = translated_prompt[0]
logger.info(f"Translated prompt to English: {prompt_to_process}")
else:
prompt_to_process = prompt
logger.info("Prompt already in English, no translation needed")
decoded = await llm_manager.chat_v2(img, prompt_to_process)
logger.info(f"Generated English response: {decoded}")
if tgt_lang != "eng_Latn":
translated_response = await perform_internal_translation(
sentences=[decoded],
src_lang="eng_Latn",
tgt_lang=tgt_lang
)
final_response = translated_response[0]
logger.info(f"Translated response to {tgt_lang}: {final_response}")
else:
final_response = decoded
logger.info("Response kept in English, no translation needed")
else:
if src_lang != "eng_Latn":
translated_prompt = await perform_internal_translation(
sentences=[prompt],
src_lang=src_lang,
tgt_lang="eng_Latn"
)
prompt_to_process = translated_prompt[0]
logger.info(f"Translated prompt to English: {prompt_to_process}")
else:
prompt_to_process = prompt
logger.info("Prompt already in English, no translation needed")
decoded = await llm_manager.generate(prompt_to_process, settings.max_tokens)
logger.info(f"Generated English response: {decoded}")
if tgt_lang != "eng_Latn":
translated_response = await perform_internal_translation(
sentences=[decoded],
src_lang="eng_Latn",
tgt_lang=tgt_lang
)
final_response = translated_response[0]
logger.info(f"Translated response to {tgt_lang}: {final_response}")
else:
final_response = decoded
logger.info("Response kept in English, no translation needed")
return ChatResponse(response=final_response)
except Exception as e:
logger.error(f"Error processing request: {str(e)}")
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
@app.post("/transcribe/", response_model=TranscriptionResponse)
async def transcribe_audio(file: UploadFile = File(...), language: str = Query(..., enum=list(asr_manager.model_language.keys()))):
if not asr_manager.model:
raise HTTPException(status_code=503, detail="ASR model still loading, please try again later")
try:
wav, sr = torchaudio.load(file.file)
wav = torch.mean(wav, dim=0, keepdim=True)
target_sample_rate = 16000
if sr != target_sample_rate:
resampler = torchaudio.transforms.Resample(orig_freq=sr, new_freq=target_sample_rate)
wav = resampler(wav)
transcription_rnnt = asr_manager.model(wav, asr_manager.model_language[language], "rnnt")
return TranscriptionResponse(text=transcription_rnnt)
except Exception as e:
logger.error(f"Error in transcription: {str(e)}")
raise HTTPException(status_code=500, detail=f"Transcription failed: {str(e)}")
@app.post("/v1/speech_to_speech")
async def speech_to_speech(
request: Request,
file: UploadFile = File(...),
language: str = Query(..., enum=list(asr_manager.model_language.keys())),
) -> StreamingResponse:
if not tts_manager.model:
raise HTTPException(status_code=503, detail="TTS model still loading, please try again later")
transcription = await transcribe_audio(file, language)
logger.info(f"Transcribed text: {transcription.text}")
chat_request = ChatRequest(
prompt=transcription.text,
src_lang=LANGUAGE_TO_SCRIPT.get(language, "kan_Knda"),
tgt_lang=LANGUAGE_TO_SCRIPT.get(language, "kan_Knda")
)
processed_text = await chat(request, chat_request)
logger.info(f"Processed text: {processed_text.response}")
voice_request = KannadaSynthesizeRequest(text=processed_text.response)
audio_response = await synthesize_kannada(voice_request)
return audio_response
LANGUAGE_TO_SCRIPT = {
"kannada": "kan_Knda"
}
# Main Execution
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run the FastAPI server.")
parser.add_argument("--port", type=int, default=settings.port, help="Port to run the server on.")
parser.add_argument("--host", type=str, default=settings.host, help="Host to run the server on.")
parser.add_argument("--config", type=str, default="config_one", help="Configuration to use")
args = parser.parse_args()
def load_config(config_path="dhwani_config.json"):
with open(config_path, "r") as f:
return json.load(f)
config_data = load_config()
if args.config not in config_data["configs"]:
raise ValueError(f"Invalid config: {args.config}. Available: {list(config_data['configs'].keys())}")
selected_config = config_data["configs"][args.config]
global_settings = config_data["global_settings"]
settings.llm_model_name = selected_config["components"]["LLM"]["model"]
settings.max_tokens = selected_config["components"]["LLM"]["max_tokens"]
settings.host = global_settings["host"]
settings.port = global_settings["port"]
settings.chat_rate_limit = global_settings["chat_rate_limit"]
settings.speech_rate_limit = global_settings["speech_rate_limit"]
llm_manager = LLMManager(settings.llm_model_name)
if selected_config["components"]["ASR"]:
asr_model_name = selected_config["components"]["ASR"]["model"]
asr_manager.model_language[selected_config["language"]] = selected_config["components"]["ASR"]["language_code"]
if selected_config["components"]["Translation"]:
for translation_config in selected_config["components"]["Translation"]:
src_lang = translation_config["src_lang"]
tgt_lang = translation_config["tgt_lang"]
asyncio.create_task(model_manager.load_model(src_lang, tgt_lang, model_manager._get_model_key(src_lang, tgt_lang)))
host = args.host if args.host != settings.host else settings.host
port = args.port if args.port != settings.port else settings.port
uvicorn.run(app, host=host, port=port) |