from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, FileResponse, HTMLResponse from pydantic import BaseModel from transformers import AutoTokenizer, AutoModelForCausalLM, TextGenerationPipeline from TTS.api import TTS import uuid app = FastAPI() # Load chatbot model model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id) pipeline = TextGenerationPipeline(model=model, tokenizer=tokenizer) # Load TTS model tts = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC") class ChatRequest(BaseModel): prompt: str class TTSRequest(BaseModel): text: str @app.post("/chat") async def chat(req: ChatRequest): output = pipeline(req.prompt, max_new_tokens=100)[0]["generated_text"] return JSONResponse({"response": output}) @app.post("/tts") async def tts_route(req: TTSRequest): filename = f"speech_{uuid.uuid4().hex}.wav" tts.tts_to_file(text=req.text, file_path=filename) return FileResponse(filename, media_type="audio/wav", filename=filename) @app.get("/", response_class=HTMLResponse) async def root(): with open("index.html", "r") as f: return f.read()