-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
100 lines (85 loc) · 3.34 KB
/
app.py
File metadata and controls
100 lines (85 loc) · 3.34 KB
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
import os
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from bible_comfort_service import BibleComfortService, BibleComfortQuery, BibleComfortResponse
from philosophy_comfort_service import (
PhilosophyComfortService,
PhilosophyComfortQuery,
PhilosophyComfortResponse,
)
from tts_service import TTSRequest, TTSService
# Instantiate services
comfort_service = BibleComfortService()
philosophy_service = PhilosophyComfortService()
tts_service = TTSService()
app = FastAPI(title="Comfort API (OpenAI SDK)")
# Change to your GitHub Pages domain (user page and/or project page)
ALLOWED_ORIGINS = [
"https://tninja.github.io",
"https://tninja.github.io/fastapi-helloworld"
]
app.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_ORIGINS,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/bible-comfort", response_model=BibleComfortResponse)
def bible_comfort(q: BibleComfortQuery):
# Basic validation
if not os.environ.get("OPENAI_API_KEY"):
raise HTTPException(status_code=500, detail="Server missing OPENAI_API_KEY")
try:
# Inline the previous wrapper body by delegating directly to the service
result = comfort_service.get_comfort(q)
return result
except (ValueError, RuntimeError) as e:
raise HTTPException(status_code=502, detail=str(e))
except Exception as e:
# Catch any other unexpected errors
raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
@app.post("/philosophy-comfort", response_model=PhilosophyComfortResponse)
def philosophy_comfort(q: PhilosophyComfortQuery):
# Basic validation
if not os.environ.get("OPENAI_API_KEY"):
raise HTTPException(status_code=500, detail="Server missing OPENAI_API_KEY")
try:
result = philosophy_service.get_comfort(q)
return result
except (ValueError, RuntimeError) as e:
raise HTTPException(status_code=502, detail=str(e))
except Exception as e:
# Catch any other unexpected errors
raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
@app.post("/tts")
def tts(req: TTSRequest):
if not os.environ.get("OPENAI_API_KEY"):
raise HTTPException(status_code=500, detail="Server missing OPENAI_API_KEY")
try:
temp_path, media_type = tts_service.generate_audio(
text=req.text,
language=req.language or "zh",
voice=req.voice,
fmt=req.format or "mp3",
)
def file_iterator(path: str, chunk_size: int = 8192):
with open(path, "rb") as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
yield chunk
try:
os.remove(path)
except Exception:
pass
return StreamingResponse(file_iterator(temp_path), media_type=media_type)
except Exception as e:
# Clean up temp file if allocation happened but streaming failed
try:
if 'temp_path' in locals() and os.path.exists(temp_path):
os.remove(temp_path)
except Exception:
pass
raise HTTPException(status_code=502, detail=f"TTS failed: {e}")