Text Generation
Transformers
English
Russian
legal
CyberFuture-3 / app.py
SkillForge45's picture
Create app.py
3c5cfb7 verified
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from model import ChatBot
import uvicorn
import os
from typing import Optional
app = FastAPI()
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize chatbot
chatbot = ChatBot()
class ChatRequest(BaseModel):
prompt: str
max_length: int = 100
use_voice: bool = False
use_web: bool = True
@app.post("/chat/")
async def chat_endpoint(
prompt: Optional[str] = Form(None),
max_length: int = Form(100),
use_voice: bool = Form(False),
use_web: bool = Form(True),
audio_file: Optional[UploadFile] = File(None)
):
try:
# Handle voice input
if audio_file:
contents = await audio_file.read()
with open("temp_audio.wav", "wb") as f:
f.write(contents)
with sr.AudioFile("temp_audio.wav") as source:
audio = chatbot.voice_interface.recognizer.record(source)
prompt = chatbot.voice_interface.recognizer.recognize_google(audio)
os.remove("temp_audio.wav")
if not prompt:
raise HTTPException(status_code=400, detail="No input provided")
response = chatbot.generate_response(
prompt,
max_length=max_length,
use_web=use_web
)
if use_voice:
chatbot.voice_interface.speak(response)
return {"response": response}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/")
async def read_root():
return {"message": "Question CyberFuture..."}
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)