junaid17 commited on
Commit
dadf7b8
·
verified ·
1 Parent(s): 6e9024e

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -123
app.py DELETED
@@ -1,123 +0,0 @@
1
- from fastapi import FastAPI, UploadFile, File, HTTPException
2
- from tools import create_rag_tool, update_retriever
3
- from chatbot import app as app_graph
4
- from langchain_core.messages import HumanMessage
5
- import os
6
- from fastapi.responses import StreamingResponse, FileResponse
7
- from langchain_core.messages import AIMessage
8
- from fastapi.middleware.cors import CORSMiddleware
9
- from pydantic import BaseModel
10
- from utils import TTS, STT, TTS2
11
-
12
-
13
- app = FastAPI()
14
-
15
- app.add_middleware(
16
- CORSMiddleware,
17
- allow_origins=["*"],
18
- allow_credentials=True,
19
- allow_methods=["*"],
20
- allow_headers=["*"],
21
- )
22
-
23
- class TTSRequest(BaseModel):
24
- text: str
25
-
26
-
27
- UPLOAD_DIR = "uploads"
28
-
29
- @app.get("/")
30
- def health():
31
- return {'Status' : 'The api is live and running'}
32
-
33
- @app.post("/upload")
34
- async def upload_file(file: UploadFile = File(...)):
35
- os.makedirs(UPLOAD_DIR, exist_ok=True)
36
-
37
- file_path = os.path.join(UPLOAD_DIR, file.filename)
38
-
39
- with open(file_path, "wb") as f:
40
- f.write(await file.read())
41
-
42
- update_retriever(file_path)
43
-
44
- return {
45
- "status": "success",
46
- "filename": file.filename
47
- }
48
-
49
-
50
- @app.post("/chat")
51
- async def chat(message: str, session_id: str = "default"):
52
-
53
- async def event_generator():
54
- async for chunk in app_graph.astream(
55
- {"messages": [HumanMessage(content=message)]},
56
- config={"configurable": {"thread_id": session_id}},
57
- stream_mode="messages"
58
- ):
59
- if len(chunk) >= 1:
60
- message_chunk = chunk[0] if isinstance(chunk, tuple) else chunk
61
- if hasattr(message_chunk, 'content') and message_chunk.content:
62
- data = str(message_chunk.content).replace("\n", "\\n")
63
- yield f"data: {data}\n\n"
64
-
65
- return StreamingResponse(
66
- event_generator(),
67
- media_type="text/event-stream",
68
- headers={
69
- "Cache-Control": "no-cache",
70
- "Connection": "keep-alive",
71
- "X-Accel-Buffering": "no",
72
- "Access-Control-Allow-Origin": "*", # Important for CORS
73
- },
74
- )
75
-
76
- # ---------------- STT ---------------- #
77
-
78
- @app.post("/stt")
79
- async def transcribe_audio(file: UploadFile = File(...)):
80
- try:
81
- return await STT(file)
82
- except Exception as e:
83
- raise HTTPException(status_code=500, detail=str(e))
84
-
85
-
86
- @app.post("/tts")
87
- async def generate_tts(request: TTSRequest):
88
- try:
89
- if not request.text.strip():
90
- raise HTTPException(status_code=400, detail="Text is empty")
91
-
92
- audio_path = await TTS(text=request.text)
93
-
94
- if not os.path.exists(audio_path):
95
- raise HTTPException(status_code=500, detail="Audio file not created")
96
-
97
- return FileResponse(
98
- path=audio_path,
99
- media_type="audio/mpeg",
100
- filename="speech.mp3"
101
- )
102
-
103
- except Exception as e:
104
- raise HTTPException(status_code=500, detail=str(e))
105
-
106
- # -------------------------- TTS2 -------------------------
107
-
108
- @app.post("/tts2")
109
- async def generate_tts2(text: str):
110
- try:
111
- audio_path = await TTS2(text=text)
112
-
113
- if not os.path.exists(audio_path):
114
- raise HTTPException(status_code=500, detail="Audio generation failed")
115
-
116
- return FileResponse(
117
- path=audio_path,
118
- media_type="audio/wav",
119
- filename="speech.wav"
120
- )
121
-
122
- except Exception as e:
123
- raise HTTPException(status_code=500, detail=str(e))