연구실 과제/Dalle3

centos7에서 flask서버를 통해 google tts api사용

dongok218 2025. 2. 6. 15:50

자 일단 처음에 Mary TTS를 사용하려고함. -> java코드로 지원해주기 때문 -> 한글지원안함.
coquiTTS로 다시 사용하려고함 -> 파이썬을 사용하지만 오픈소스라 공짜이기때문 -> 씨발 또 한글 지원안함.
-->GPT좆병신새끼

결국 유료인 googleTTS사용하려고함. 
1. 구글 클라우드 페이지 접속
2. 새 프로젝트 생성
3. 결제수단 입력(씨발 여기서 또 학교 계정으로는 결제가 안 된대. 그럼 말로 알려주던가 좆같은 오류코드만 내보내서 존나 찾느라 시간보냄)->결국 내 개인계정으로 함
4. IAM및 관리자->서비스계정->서비스계정 생성(json형식으로 키 받아야함)
5. 해당키를 /opt/디렉토리로 보냄
6. /opt/디렉토리에서 server.py코드 작성.
7.  server.py를 실행해봤더니 실행은 되는데 curl명령어로 flask서버에 명령어를 보내도 아무 응답이 없음
8. 씨발 알고보니까 포트를 열지않음;

[sskim@localhost ~]$ netstat -tulnp | grep 5002
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        0      0 0.0.0.0:5002            0.0.0.0:*               LISTEN      -
[sskim@localhost ~]$ su -
암호:
[root@localhost ~]# netstat -tulnp | grep 5002
tcp        0      0 0.0.0.0:5002            0.0.0.0:*               LISTEN      2134260/python3
[root@localhost ~]# sudo firewall-cmd --list-ports
21/tcp 22/tcp 3306/tcp 8080/tcp 8888/tcp 9092/tcp
[root@localhost ~]# sudo firewall-cmd --zone=public --add-port=5002/tcp --permanent
success
[root@localhost ~]# sudo firewall-cmd --reload
success
[root@localhost ~]# sudo firewall-cmd --list-ports
21/tcp 22/tcp 3306/tcp 5002/tcp 8080/tcp 8888/tcp 9092/tcp



이런식으로 포트 열고 확인해줌.
9. 씨발 여전히 안됨 ㅋㅋ
10. GOOGLE_APPLICATION_CREDENTIALS 환경 변수 설정 이번엔 또 구글 환경변수 설정이 안되어있음.(이게 뭔데요 씨발 ㅋㅋ)
11. [root@localhost opt]# export GOOGLE_APPLICATION_CREDENTIALS="/opt/dilabtts-da637c7e3b0e.json"
이 명령어로 구글 환경변수 수동으로 설정해줌
12. 하...포트도 열고, SELinux확인해서 getenforce했을때 Enforcing상태여서 sudo setenforce 0로도 해준다음 실행해도 안됨. 뭐가 문제야 진짜 씨발

 

 


<Flask서버 자체 확인>

- Flask서버 자체가 문제가 있을수 있다고 판단하여 flask를 실행하고 간단한 예문으로 정상적으로 동작하나 확인해봄.

1. 파이썬과 Flask 제대로 설치되어 있는지 버전 확인

버전확인

 

2. 간단하게 테스트할 app.py작성

app.py

3. 플라스크 실행후 127.0.0.1:5000 웹페이지 들어가보면 hello출력되는거 확인 가능.

▶ 결론: flask는 정상인거 확인

 


 

<curl명령문 동작 확인>

'curl --version'으로 확인해보니 매우 정상인것으로 확인.

 


★해결★

알고보니 curl명령어를 flask서버 실행시킨 후 그 flask명령창에다가 쓰는게 아니라 centos7명령창에다가 쓰는거였음.

이것땜에 하루를 버리다니 참 개탄스럽구만.

 

from flask import Flask, request, send_file, jsonify
from google.cloud import texttospeech
import os
import sys

app = Flask(__name__)

# 환경 변수 설정 (이미 설정되어 있다면 생략)
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/opt/dilabtts-da637c7e3b0e.json"

try:
    client = texttospeech.TextToSpeechClient()
except Exception as e:
    print("ERROR: Google TTS 클라이언트 초기화 실패:", e)
    sys.stdout.flush()
    exit(1)

@app.route('/ping', methods=['GET'])
def ping():
    print("INFO: /ping 엔드포인트 호출됨")
    sys.stdout.flush()
    return "pong", 200

@app.route('/')
def home():
    return "Welcome to Flask Server!", 200


@app.route('/api/tts', methods=['POST'])
def generate_tts():
    print("INFO: /api/tts 엔드포인트 호출됨")
    sys.stdout.flush()

    if not request.is_json:
        print("ERROR: Content-Type이 application/json이 아님")
        sys.stdout.flush()
        return jsonify({"error": "Content-Type must be application/json"}), 400

    data = request.get_json()
    text = data.get("text")
    print("INFO: 요청된 텍스트:", text)
    sys.stdout.flush()

    if not text:
        print("ERROR: 요청된 텍스트가 없음")
        sys.stdout.flush()
        return jsonify({"error": "No text provided"}), 400

    synthesis_input = texttospeech.SynthesisInput(text=text)
    voice = texttospeech.VoiceSelectionParams(
        language_code="ko-KR",
        ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL
    )
    audio_config = texttospeech.AudioConfig(
        audio_encoding=texttospeech.AudioEncoding.LINEAR16
    )

    try:
        print("INFO: Google TTS API 호출 시작...")
        sys.stdout.flush()
        response = client.synthesize_speech(
        input=synthesis_input,
            voice=voice,
            audio_config=audio_config
        )
    except Exception as e:
        print("ERROR: Google TTS API 호출 실패:", e)
        sys.stdout.flush()
        return jsonify({"error": "Google TTS API call failed", "details": str(e)}), 500

    output_path = "output.wav"
    try:
        with open(output_path, "wb") as out_file:
            if response.audio_content:
                out_file.write(response.audio_content)
                print("INFO: output.wav 파일 생성 완료!")
            else:
                print("ERROR: Google TTS 응답이 비어 있음")
                sys.stdout.flush()
                return jsonify({"error": "Empty audio content from TTS API"}), 500
    except Exception as e:
        print("ERROR: output.wav 파일 저장 실패:", e)
        sys.stdout.flush()
        return jsonify({"error": "Failed to write audio file", "details": str(e)}), 500

    sys.stdout.flush()
    return send_file(output_path, mimetype="audio/wav", as_attachment=True)

if __name__ == '__main__':
    print("INFO: Google TTS Flask 서버 시작됨!")
    sys.stdout.flush()
    app.run(host="0.0.0.0", port=5002, debug=True)

[google api를 사용하기 위한 server.py]