PyxiLabs commited on
Commit
41a6ecd
·
verified ·
1 Parent(s): 23c12da

Update core/app.py

Browse files
Files changed (1) hide show
  1. core/app.py +45 -8
core/app.py CHANGED
@@ -6,12 +6,33 @@ from pydantic import BaseModel, Field
6
  from typing import Optional
7
  from vocify import generate_speech
8
  import os
 
 
 
 
9
 
10
  # Create necessary directories if they don't exist
11
  os.makedirs("static", exist_ok=True)
12
  os.makedirs("templates", exist_ok=True)
13
 
14
- app = FastAPI(title="Pyxilabs._.Vocify", description="A Text-to-Speech API", swagger_ui_parameters={"favicon": "/static/icon.png"})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  # Mount static files directory
17
  app.mount("/static", StaticFiles(directory="static"), name="static")
@@ -47,27 +68,39 @@ MODEL_INFO = {
47
  }
48
  }
49
 
 
 
 
 
 
 
 
 
50
  class SpeechRequest(BaseModel):
51
  model: Optional[str] = Field(default="Pyx r1-voice")
52
  input: str = Field(..., max_length=5000)
53
  voice: str
54
 
 
55
  @app.post("/v1/audio/speech")
56
  @app.get("/v1/audio/speech")
57
- async def create_speech(request: SpeechRequest):
 
 
 
58
  try:
59
- if request.model != "Pyx r1-voice":
60
  raise HTTPException(status_code=400, detail="Invalid model. Only 'Pyx r1-voice' is supported.")
61
 
62
- if request.voice not in MODEL_INFO["Pyx r1-voice"]["voices"]:
63
  raise HTTPException(status_code=400, detail="Invalid voice ID")
64
 
65
- voice_id = MODEL_INFO["Pyx r1-voice"]["voices"][request.voice]
66
 
67
  result = generate_speech(
68
  model="eleven_multilingual_v2",
69
  voice=voice_id,
70
- input_text=request.input
71
  )
72
 
73
  if isinstance(result, list):
@@ -78,6 +111,7 @@ async def create_speech(request: SpeechRequest):
78
  except Exception as e:
79
  raise HTTPException(status_code=500, detail=str(e))
80
 
 
81
  @app.get("/v1/models")
82
  async def get_models():
83
  models_response = []
@@ -98,15 +132,18 @@ async def get_models():
98
 
99
  return {"models": models_response}
100
 
 
101
  @app.get("/", response_class=HTMLResponse)
102
  async def root(request: Request):
103
  with open("templates/index.html", "r") as file:
104
  return HTMLResponse(content=file.read())
105
 
106
- app.get("/favicon.ico", include_in_schema=False)
 
107
  async def favicon():
108
  return {"url": "/static/icon.png"}
109
-
 
110
  if __name__ == "__main__":
111
  import uvicorn
112
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
6
  from typing import Optional
7
  from vocify import generate_speech
8
  import os
9
+ from slowapi import Limiter
10
+ from slowapi.util import get_remote_address
11
+ from slowapi.errors import RateLimitExceeded
12
+ from fastapi.middleware.cors import CORSMiddleware
13
 
14
  # Create necessary directories if they don't exist
15
  os.makedirs("static", exist_ok=True)
16
  os.makedirs("templates", exist_ok=True)
17
 
18
+ # Initialize FastAPI app
19
+ app = FastAPI(
20
+ title="Pyxilabs._.Vocify",
21
+ description="A Text-to-Speech API",
22
+ swagger_ui_parameters={"favicon": "/static/icon.png"}
23
+ )
24
+
25
+ # Rate Limiter Setup
26
+ limiter = Limiter(key_func=get_remote_address)
27
+ app.state.limiter = limiter
28
+
29
+ # Rate limit error handler
30
+ @app.exception_handler(RateLimitExceeded)
31
+ async def rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded):
32
+ return HTTPException(
33
+ status_code=429,
34
+ detail="Rate limit exceeded. Please try again later."
35
+ )
36
 
37
  # Mount static files directory
38
  app.mount("/static", StaticFiles(directory="static"), name="static")
 
68
  }
69
  }
70
 
71
+ # Rate limits for free tier
72
+ RATE_LIMITS = {
73
+ "rpm": 10, # Requests per minute
74
+ "rph": 100, # Requests per hour
75
+ "rpd": 1000, # Requests per day
76
+ }
77
+
78
+ # Pydantic model for speech request
79
  class SpeechRequest(BaseModel):
80
  model: Optional[str] = Field(default="Pyx r1-voice")
81
  input: str = Field(..., max_length=5000)
82
  voice: str
83
 
84
+ # Endpoint to generate speech
85
  @app.post("/v1/audio/speech")
86
  @app.get("/v1/audio/speech")
87
+ @limiter.limit(f"{RATE_LIMITS['rpm']}/minute")
88
+ @limiter.limit(f"{RATE_LIMITS['rph']}/hour")
89
+ @limiter.limit(f"{RATE_LIMITS['rpd']}/day")
90
+ async def create_speech(request: Request, speech_request: SpeechRequest):
91
  try:
92
+ if speech_request.model != "Pyx r1-voice":
93
  raise HTTPException(status_code=400, detail="Invalid model. Only 'Pyx r1-voice' is supported.")
94
 
95
+ if speech_request.voice not in MODEL_INFO["Pyx r1-voice"]["voices"]:
96
  raise HTTPException(status_code=400, detail="Invalid voice ID")
97
 
98
+ voice_id = MODEL_INFO["Pyx r1-voice"]["voices"][speech_request.voice]
99
 
100
  result = generate_speech(
101
  model="eleven_multilingual_v2",
102
  voice=voice_id,
103
+ input_text=speech_request.input
104
  )
105
 
106
  if isinstance(result, list):
 
111
  except Exception as e:
112
  raise HTTPException(status_code=500, detail=str(e))
113
 
114
+ # Endpoint to get available models
115
  @app.get("/v1/models")
116
  async def get_models():
117
  models_response = []
 
132
 
133
  return {"models": models_response}
134
 
135
+ # Root endpoint to serve the HTML frontend
136
  @app.get("/", response_class=HTMLResponse)
137
  async def root(request: Request):
138
  with open("templates/index.html", "r") as file:
139
  return HTMLResponse(content=file.read())
140
 
141
+ # Favicon endpoint
142
+ @app.get("/favicon.ico", include_in_schema=False)
143
  async def favicon():
144
  return {"url": "/static/icon.png"}
145
+
146
+ # Run the application
147
  if __name__ == "__main__":
148
  import uvicorn
149
  uvicorn.run(app, host="0.0.0.0", port=7860)