Skip to content

Commit 05c43f4

Browse files
committed
format, send multiple texts
1 parent 3a952d5 commit 05c43f4

File tree

2 files changed

+50
-76
lines changed

2 files changed

+50
-76
lines changed

test_server.py

Lines changed: 43 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -5,23 +5,61 @@
55

66
start_time = datetime.now()
77

8-
def send():
8+
output_directory = "./outputs/"
99

10-
# url = "http://127.0.0.1:7851/api/tts-generate/"
1110

11+
def send():
1212
url = "http://127.0.0.1:8000/api/synthesize/"
13-
13+
1414
txt1 = "1번. 또 파이썬은 순수한 프로그램 언어로서의 기능 외에도 다른 언어로 쓰인 모듈들을 연결하는 접착제 언어로써 자주 이용된다. 실제 파이썬은 많은 상용 응용 프로그램에서 스크립트 언어로 채용되고 있다. 도움말 문서도 정리가 잘 되어 있으며, 유니코드 문자열을 지원해서 다양한 언어의 문자 처리에도 능하다."
1515
txt2 = "2번. 파이썬에서는 들여쓰기를 사용해서 블록을 구분하는 독특한 문법을 채용하고 있다. 이 문법은 파이썬에 익숙한 사용자나 기존 프로그래밍 언어에서 들여쓰기의 중요성을 높이 평가하는 사용자에게는 잘 받아들여지고 있지만, 다른 언어의 사용자에게서는 프로그래머의 코딩 스타일을 제한한다는 비판도 많다."
1616
txt3 = "3번. 파이썬은 1980년대 말 고안되어 네덜란드 CWI의 귀도 반 로섬이 1989년 12월 구현하기 시작하였다. 이는 역시 SETL에서 영감을 받은 ABC 언어의 후계로서 예외 처리가 가능하고, 아메바 OS와 연동이 가능하였다. 반 로섬은 파이썬의 주 저자로 계속 중심적 역할을 맡아 파이썬의 방향을 결정하여, 파이썬 공동체로부터 '자선 종신 이사'의 칭호를 부여받았다. 이 같은 예로는 리눅스의 리누스 토발즈 등이 있다."
1717

1818
txt_arr = [txt1, txt2, txt3]
1919

20-
2120
current_datetime = datetime.now()
2221
date_format = current_datetime.strftime("%Y%m%d%H%M%S")
2322
date_format = date_format + str(current_datetime.microsecond)
24-
23+
24+
for i, t in enumerate(txt_arr):
25+
data = {"languageCode": "ko-KR", "name": "ko-KR-Standard-B", "text": str(t)}
26+
try:
27+
response = requests.post(url, data=json.dumps(data), verify=False)
28+
response.raise_for_status()
29+
30+
with open(output_directory + "melo_" + date_format + "_" + str(i) + ".txt", "a") as the_file:
31+
the_file.write(response.text)
32+
33+
except requests.exceptions.RequestException as e:
34+
print(f"Request error: {e}")
35+
except ValueError as e:
36+
print(f"JSON parsing error: {e}")
37+
except Exception as e:
38+
print(f"An error occurred: {e}")
39+
40+
# single text
41+
# data = {
42+
# "languageCode": "ko-KR",
43+
# "name": "ko-KR-Standard-B",
44+
# "text": str(txt1)
45+
# }
46+
# try:
47+
# response = requests.post(url, data=json.dumps(data), verify=False)
48+
# response.raise_for_status()
49+
# # print(response)
50+
# # rsp = response.text
51+
# # pprint(rsp)
52+
53+
# with open('somefile.txt', 'a') as the_file:
54+
# the_file.write(response.text)
55+
56+
# except requests.exceptions.RequestException as e:
57+
# print(f"Request error: {e}")
58+
# except ValueError as e:
59+
# print(f"JSON parsing error: {e}")
60+
# except Exception as e:
61+
# print(f"An error occurred: {e}")
62+
2563
# data = {
2664
# "voice": {
2765
# "languageCode": "ko-KR",
@@ -35,38 +73,7 @@ def send():
3573
# }
3674
# }
3775

38-
data = {
39-
"languageCode": "ko-KR",
40-
"name": "ko-KR-Standard-B",
41-
"text": str(txt1)
42-
}
43-
44-
#convert data to json
45-
46-
47-
try:
48-
response = requests.post(url, data=json.dumps(data), verify=False)
49-
response.raise_for_status()
50-
# print(response)
51-
# rsp = response.text
52-
# pprint(rsp)
53-
54-
with open('somefile.txt', 'a') as the_file:
55-
the_file.write(response.text)
56-
57-
except requests.exceptions.RequestException as e:
58-
print(f"Request error: {e}")
59-
except ValueError as e:
60-
print(f"JSON parsing error: {e}")
61-
except Exception as e:
62-
print(f"An error occurred: {e}")
6376

6477
if __name__ == "__main__":
6578
send()
6679
print(f"Elapsed time: {datetime.now() - start_time}")
67-
68-
69-
70-
71-
72-

tts_server.py

Lines changed: 7 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,12 @@
11
import uvicorn
2-
# from typing import Any
32
from fastapi import FastAPI, Request
43

5-
from typing import Any, Dict, AnyStr, List, Union
64
from melo.api import TTS
7-
from pydantic import BaseModel
8-
9-
10-
from typing import Dict
11-
12-
import json
135

146

157
speed = 1.0
16-
device = 'cuda:0'
17-
18-
# text = "안녕하세요! 오늘은 날씨가 정말 좋네요."
19-
model = TTS(language='KR', device=device)
8+
device = "cuda:0"
9+
model = TTS(language="KR", device=device)
2010

2111
app = FastAPI()
2212

@@ -30,43 +20,20 @@
3020
# )
3121

3222

33-
class TtsPostRequest(BaseModel):
34-
languageCode: str | None = None
35-
name: str| None = None
36-
text: str
37-
38-
# voice: dict[str, str]
39-
# input: dict[str, str]
40-
# audioconfig: dict[str, str]
41-
42-
4323
@app.get("/")
4424
async def root():
4525
return {"message": "Hello World"}
4626

4727

4828
@app.post("/api/synthesize")
49-
async def apifunction_generate_tts(request: Request):
29+
async def apifunction_generate_tts(request: Request):
5030
_json = await request.json()
51-
# => ('{"languageCode":"ko-KR","name":"ko-KR-Standard-B","text":"1번. 또 파이썬은 순수한 ''프로그램 언어로서의 기능 외에도 다른 언어로 쓰인 모듈들을 연결하는 접착제 언어로써 자주 이용된다. 실제 파이썬은 많은 상용 응용 ''프로그램에서 스크립트 언어로 채용되고 있다. 도움말 문서도 정리가 잘 되어 있으며, 유니코 드 문자열을 지원해서 다양한 언어의 문자 ' '처리에도 능하다."}')
52-
# get text
53-
text = _json['text']
54-
55-
print(text)
56-
57-
speaker_ids = model.hps.data.spk2id
58-
# # output_path = 'kr.wav'
59-
# # model.tts_to_file(data, speaker_ids['KR'], output_path, speed=speed)
60-
61-
response_data = model.tts_to_base64(text, speaker_ids['KR'], speed=speed)
62-
63-
64-
31+
text = _json["text"]
6532

33+
speaker_ids = model.hps.data.spk2id
34+
response_data = model.tts_to_base64(text, speaker_ids["KR"], speed=speed)
6635
return response_data
6736

6837

69-
70-
7138
if __name__ == "__main__":
72-
uvicorn.run("main:app", host="127.0.0.1", port=5000, log_level="info")
39+
uvicorn.run("main:app", host="127.0.0.1", port=5000, log_level="info")

0 commit comments

Comments
 (0)