Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
|
| 2 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from pydantic import BaseModel
|
| 4 |
+
from model import ChatBot
|
| 5 |
+
import uvicorn
|
| 6 |
+
import os
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
app = FastAPI()
|
| 10 |
+
|
| 11 |
+
# CORS middleware
|
| 12 |
+
app.add_middleware(
|
| 13 |
+
CORSMiddleware,
|
| 14 |
+
allow_origins=["*"],
|
| 15 |
+
allow_methods=["*"],
|
| 16 |
+
allow_headers=["*"],
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# Initialize chatbot
|
| 20 |
+
chatbot = ChatBot()
|
| 21 |
+
|
| 22 |
+
class ChatRequest(BaseModel):
|
| 23 |
+
prompt: str
|
| 24 |
+
max_length: int = 100
|
| 25 |
+
use_voice: bool = False
|
| 26 |
+
use_web: bool = True
|
| 27 |
+
|
| 28 |
+
@app.post("/chat/")
|
| 29 |
+
async def chat_endpoint(
|
| 30 |
+
prompt: Optional[str] = Form(None),
|
| 31 |
+
max_length: int = Form(100),
|
| 32 |
+
use_voice: bool = Form(False),
|
| 33 |
+
use_web: bool = Form(True),
|
| 34 |
+
audio_file: Optional[UploadFile] = File(None)
|
| 35 |
+
):
|
| 36 |
+
try:
|
| 37 |
+
# Handle voice input
|
| 38 |
+
if audio_file:
|
| 39 |
+
contents = await audio_file.read()
|
| 40 |
+
with open("temp_audio.wav", "wb") as f:
|
| 41 |
+
f.write(contents)
|
| 42 |
+
|
| 43 |
+
with sr.AudioFile("temp_audio.wav") as source:
|
| 44 |
+
audio = chatbot.voice_interface.recognizer.record(source)
|
| 45 |
+
prompt = chatbot.voice_interface.recognizer.recognize_google(audio)
|
| 46 |
+
os.remove("temp_audio.wav")
|
| 47 |
+
|
| 48 |
+
if not prompt:
|
| 49 |
+
raise HTTPException(status_code=400, detail="No input provided")
|
| 50 |
+
|
| 51 |
+
response = chatbot.generate_response(
|
| 52 |
+
prompt,
|
| 53 |
+
max_length=max_length,
|
| 54 |
+
use_web=use_web
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
if use_voice:
|
| 58 |
+
chatbot.voice_interface.speak(response)
|
| 59 |
+
|
| 60 |
+
return {"response": response}
|
| 61 |
+
|
| 62 |
+
except Exception as e:
|
| 63 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 64 |
+
|
| 65 |
+
@app.get("/")
|
| 66 |
+
async def read_root():
|
| 67 |
+
return {"message": "Question CyberFuture..."}
|
| 68 |
+
|
| 69 |
+
if __name__ == "__main__":
|
| 70 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|