Mbonea commited on
Commit
0d7df26
·
1 Parent(s): dc23243

pitts should work

Browse files
App/TTS/Schemas.py CHANGED
@@ -30,6 +30,11 @@ class DescriptTranscript(BaseModel):
30
  file_extenstion: str = ".wav"
31
 
32
 
 
 
 
 
 
33
  class DescriptRequest(BaseModel):
34
  text: str
35
  speaker: Optional[str] = Field(default="Lawrance")
 
30
  file_extenstion: str = ".wav"
31
 
32
 
33
+ class PiTTSRequest(BaseModel):
34
+ text: str
35
+ voice: Optional[str]
36
+
37
+
38
  class DescriptRequest(BaseModel):
39
  text: str
40
  speaker: Optional[str] = Field(default="Lawrance")
App/TTS/TTSRoutes.py CHANGED
@@ -9,13 +9,19 @@ from .Schemas import (
9
  DescriptStatusRequest,
10
  DescriptSfxRequest,
11
  DescriptTranscript,
 
12
  )
13
  from .utils.Podcastle import PodcastleAPI
14
  from .utils.HeyGen import HeygenAPI
 
15
  from .utils.Descript import DescriptTTS
16
  import os
17
  import asyncio
18
 
 
 
 
 
19
  tts_router = APIRouter(tags=["TTS"])
20
  data = {"username": os.environ.get("USERNAME"), "password": os.environ.get("PASSWORD")}
21
  tts = PodcastleAPI(**data)
@@ -27,6 +33,7 @@ data = {
27
 
28
  descript_tts = DescriptTTS()
29
  heyGentts = HeygenAPI(**data)
 
30
 
31
 
32
  @tts_router.post("/generate_tts")
@@ -86,3 +93,44 @@ async def auto_refresh():
86
  @tts_router.post("/status")
87
  async def search_id(req: StatusRequest):
88
  return await tts.check_status(req)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  DescriptStatusRequest,
10
  DescriptSfxRequest,
11
  DescriptTranscript,
12
+ PiTTSRequest,
13
  )
14
  from .utils.Podcastle import PodcastleAPI
15
  from .utils.HeyGen import HeygenAPI
16
+ from .utils.Pi import PiAIClient
17
  from .utils.Descript import DescriptTTS
18
  import os
19
  import asyncio
20
 
21
+ from fastapi import FastAPI, Request, HTTPException
22
+ from fastapi.responses import StreamingResponse, FileResponse
23
+ import os
24
+
25
  tts_router = APIRouter(tags=["TTS"])
26
  data = {"username": os.environ.get("USERNAME"), "password": os.environ.get("PASSWORD")}
27
  tts = PodcastleAPI(**data)
 
33
 
34
  descript_tts = DescriptTTS()
35
  heyGentts = HeygenAPI(**data)
36
+ pi = PiAIClient()
37
 
38
 
39
  @tts_router.post("/generate_tts")
 
93
  @tts_router.post("/status")
94
  async def search_id(req: StatusRequest):
95
  return await tts.check_status(req)
96
+
97
+
98
+ @tts_router.post("/pi_tts")
99
+ async def pi_tts(req: PiTTSRequest):
100
+ return await pi.say(text=req.text, voice=req.voice)
101
+
102
+
103
+ @tts_router.get("/audio/{audio_name}")
104
+ async def serve_audio(request: Request, audio_name: str):
105
+ audio_directory = "/tmp/Audio"
106
+ audio_path = os.path.join(audio_directory, audio_name)
107
+ if not os.path.isfile(audio_path):
108
+ raise HTTPException(status_code=404, detail="Audio not found")
109
+
110
+ range_header = request.headers.get("Range", None)
111
+ audio_size = os.path.getsize(audio_path)
112
+
113
+ if range_header:
114
+ start, end = range_header.strip().split("=")[1].split("-")
115
+ start = int(start)
116
+ end = audio_size if end == "" else int(end)
117
+
118
+ headers = {
119
+ "Content-Range": f"bytes {start}-{end}/{audio_size}",
120
+ "Accept-Ranges": "bytes",
121
+ # Optionally, you might want to force download by uncommenting the next line:
122
+ # "Content-Disposition": f"attachment; filename={audio_name}",
123
+ }
124
+
125
+ content = read_file_range(audio_path, start, end)
126
+ return StreamingResponse(content, media_type="audio/mpeg", headers=headers)
127
+
128
+ return FileResponse(audio_path, media_type="audio/mpeg")
129
+
130
+
131
+ def read_file_range(path, start, end):
132
+ """Helper function to read specific range of bytes from a file."""
133
+ with open(path, "rb") as file:
134
+ file.seek(start)
135
+ # Be sure to handle the case where `end` is not the last byte
136
+ return file.read(end - start + 1)
App/TTS/utils/Pi.py ADDED
@@ -0,0 +1,189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import aiohttp
2
+ import asyncio
3
+ import enum
4
+ import requests
5
+ import os
6
+ from functools import cache
7
+ import tempfile
8
+ import uuid
9
+
10
+
11
+ class VoiceType(enum.Enum):
12
+ voice1 = "voice1"
13
+ voice2 = "voice2"
14
+ voice3 = "voice3"
15
+ voice4 = "voice4"
16
+ voice5 = "voice5"
17
+ voice5_update = "voice5-update"
18
+ voice6 = "voice6"
19
+ voice7 = "voice7"
20
+ voice8 = "voice8"
21
+ voice9 = "voice9"
22
+ voice10 = "voice10"
23
+ voice11 = "voice11"
24
+ voice12 = "voice12"
25
+ qdpi = "qdpi"
26
+
27
+
28
+ class PiAIClient:
29
+ def __init__(self):
30
+ self.dir = "/tmp/Audio"
31
+ self.base_url = "https://pi.ai/api/chat"
32
+ self.referer = "https://pi.ai/talk"
33
+ self.origin = "https://pi.ai"
34
+ self.user_agent = (
35
+ "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/113.0"
36
+ )
37
+ self.cookie = None
38
+ self.headers = {
39
+ "User-Agent": self.user_agent,
40
+ "Accept": "text/event-stream",
41
+ "Referer": self.referer,
42
+ "X-Api-Version": "3",
43
+ "Content-Type": "application/json",
44
+ "Origin": self.origin,
45
+ "Connection": "keep-alive",
46
+ "Sec-Fetch-Dest": "empty",
47
+ "Sec-Fetch-Mode": "no-cors",
48
+ "Sec-Fetch-Site": "same-origin",
49
+ "DNT": "1",
50
+ "Sec-GPC": "1",
51
+ "TE": "trailers",
52
+ "Pragma": "no-cache",
53
+ "Cache-Control": "no-cache",
54
+ }
55
+
56
+ async def get_cookie(self) -> str:
57
+ headers = self.headers.copy()
58
+ async with aiohttp.ClientSession() as session:
59
+ async with session.post(
60
+ f"{self.base_url}/start", headers=headers, json={}
61
+ ) as response:
62
+ self.cookie = response.headers["Set-Cookie"]
63
+ return self.cookie
64
+
65
+ async def make_request(
66
+ self, endpoint: str, headers: dict, json: dict = None, method: str = "POST"
67
+ ):
68
+ async with aiohttp.ClientSession() as session:
69
+ if method == "POST":
70
+ async with session.post(
71
+ endpoint, headers=headers, json=json
72
+ ) as response:
73
+ return await response.text()
74
+ elif method == "GET":
75
+ async with session.get(endpoint, headers=headers) as response:
76
+ return response
77
+
78
+ async def get_response(self, input_text) -> tuple[list[str], list[str]]:
79
+ if self.cookie is None:
80
+ self.cookie = await self.get_cookie()
81
+
82
+ headers = self.headers.copy()
83
+ headers["Cookie"] = self.cookie
84
+
85
+ data = {"text": input_text}
86
+ response_text = await self.make_request(self.base_url, headers, json=data)
87
+
88
+ response_lines = response_text.split("\n")
89
+ response_texts = []
90
+ response_sids = []
91
+ print(response_lines)
92
+ for line in response_lines:
93
+ if line.startswith('data: {"text":"'):
94
+ start = len('data: {"text":')
95
+ end = line.rindex("}")
96
+ text_dict = line[start + 1 : end - 1].strip()
97
+ response_texts.append(text_dict)
98
+ elif line.startswith('data: {"sid":'):
99
+ start = len('data: {"sid":')
100
+ end = line.rindex("}")
101
+ sid_dict = line[start : end - 1].strip()
102
+ sid_dict = sid_dict.split(",")[0][1:-1]
103
+ response_sids.append(sid_dict)
104
+
105
+ return response_texts, response_sids
106
+
107
+ async def speak_response(
108
+ self, message_sid: str, voice: VoiceType = VoiceType.voice4
109
+ ) -> None:
110
+ if self.cookie is None:
111
+ self.cookie = await self.get_cookie()
112
+
113
+ headers = self.headers.copy()
114
+ headers.update(
115
+ {
116
+ "Host": "pi.ai",
117
+ "Accept": "audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5",
118
+ "Accept-Language": "en-US,en;q=0.9",
119
+ "Range": "bytes=0-",
120
+ "Sec-Fetch-Dest": "audio",
121
+ "Sec-Fetch-Mode": "no-cors",
122
+ "Sec-Fetch-Site": "same-origin",
123
+ "Sec-CH-UA": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
124
+ "Sec-CH-UA-Mobile": "?0",
125
+ "Sec-CH-UA-Platform": '"Windows"',
126
+ }
127
+ )
128
+
129
+ headers = {
130
+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/113.0",
131
+ "Accept": "audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5",
132
+ "Accept-Language": "en-US,en;q=0.5",
133
+ "Range": "bytes=0-",
134
+ "Connection": "keep-alive",
135
+ "Referer": "https://pi.ai/talk",
136
+ # "Cookie": cookie,
137
+ "Sec-Fetch-Dest": "audio",
138
+ "Sec-Fetch-Mode": "no-cors",
139
+ "Sec-Fetch-Site": "same-origin",
140
+ "DNT": "1",
141
+ "Sec-GPC": "1",
142
+ "Accept-Encoding": "identity",
143
+ "TE": "trailers",
144
+ }
145
+ headers["Cookie"] = self.cookie
146
+ print(headers)
147
+ endpoint = f"{self.base_url}/voice?mode=eager&voice={voice.value}&messageSid={message_sid}"
148
+ async with aiohttp.ClientSession() as session:
149
+ async with session.get(endpoint, headers=headers) as response:
150
+ print(response.status)
151
+ file_name = str(uuid.uuid4()) + ".mp3"
152
+ file_path = os.path.join(self.dir, file_name)
153
+ os.makedirs(file_path, exist_ok=True)
154
+ if response.status == 200:
155
+ with open(file_path, "wb") as file:
156
+ async for chunk in response.content.iter_chunked(128):
157
+ file.write(chunk)
158
+ return {
159
+ "url": f"https://yakova-embedding.hf.space/audio/{file_name}"
160
+ }
161
+ # Run command vlc to play the audio file
162
+ # os.system("vlc speak.wav --intf dummy --play-and-exit")
163
+ else:
164
+ temp = await response.text()
165
+ print(temp)
166
+ return "Error: Unable to retrieve audio."
167
+
168
+ async def say(self, text, voice=VoiceType.qdpi):
169
+ _, response_sids = await self.get_response(text)
170
+
171
+ if response_sids:
172
+ return await self.speak_response(response_sids[0], voice=voice)
173
+
174
+
175
+ # async def main():
176
+ # client = PiAIClient()
177
+ # response_texts, response_sids = await client.get_response(
178
+ # "Write a ryme to introduce yourself."
179
+ # )
180
+ # print(response_texts, response_sids)
181
+ # import time
182
+
183
+ # if response_sids:
184
+ # return await client.speak_response(response_sids[1])
185
+
186
+
187
+ # # Run the main function
188
+ # if __name__ == "__main__":
189
+ # asyncio.run(main())
App/TTS/utils/Picsart.py DELETED
@@ -1,33 +0,0 @@
1
- import asyncio
2
- from playwright.async_api import async_playwright
3
-
4
- async def extract_bootstrap_data():
5
- async with async_playwright() as p:
6
- browser = await p.chromium.launch()
7
- page = await browser.new_page()
8
-
9
- # Navigate to the Pixabay Sound Effects page
10
- await page.goto('https://pixabay.com/sound-effects/search/door%20creaking/')
11
-
12
- # Wait for the content to load (you can adjust the timeout as needed)
13
- # await page.wait_for_selector('.js-media-list-wrapper')
14
- # await page.wait_for_selector('.js-media-item')
15
-
16
- # Get the content of the 5th script tag
17
- # script_content = await page.evaluate('''() => {
18
- # const scripty=document.querySelectorAll('script')[0];
19
- # return scripty.content
20
- # }''')
21
- # print(script_content)
22
- # await page.evaluate(f'''{script_content}(''')
23
-
24
- page_content = await page.content()
25
- # Print the content of the 5th script tag
26
- # print(page_content)
27
-
28
- # Close the browser
29
- await browser.close()
30
-
31
- # Run the extraction function
32
- if __name__ == '__main__':
33
- asyncio.run(extract_bootstrap_data())