Spaces:
Sleeping
Sleeping
from flask import Flask, render_template, request, redirect, url_for, send_file | |
from gtts import gTTS | |
import os | |
# ここに翻訳データを格納しておく | |
from translation_data import translation_dict_A, translation_dict_B, translation_dict_C, translation_dict_D, translation_dict_F, translation_dict_G | |
app = Flask(__name__) | |
# 音声ファイルを保存するディレクトリ | |
AUDIO_DIR = 'static/audio' | |
# 英語の文章を取り出す | |
english_sentences_A = list(translation_dict_A.keys()) | |
english_sentences_B = list(translation_dict_B.keys()) | |
english_sentences_C = list(translation_dict_C.keys()) | |
english_sentences_D = list(translation_dict_D.keys()) | |
english_sentences_F = list(translation_dict_F.keys()) | |
english_sentences_G = list(translation_dict_G.keys()) | |
# 音声ファイルを生成する関数 | |
def generate_audio(text, lang='en', filename=None): | |
if filename is None: | |
filename = f"{AUDIO_DIR}/{text[:10].replace(' ', '_')}.mp3" | |
if not os.path.exists(filename): # ファイルが存在しない場合のみ生成 | |
tts = gTTS(text=text, lang=lang) | |
tts.save(filename) | |
return filename | |
# サーバー起動時にすべての英語音声ファイルを生成 | |
def generate_all_audio_files(): | |
os.makedirs(AUDIO_DIR, exist_ok=True) | |
# 各セットに対して音声ファイルを生成 | |
for sentence in english_sentences_A + english_sentences_B + english_sentences_C + english_sentences_D + english_sentences_F + english_sentences_G: | |
generate_audio(sentence, 'en') | |
# Flaskアプリ起動時に音声ファイルを生成 | |
with app.app_context(): | |
generate_all_audio_files() | |
def portal(): | |
return render_template('portal.html') | |
def index(): | |
set_name = request.args.get('set', 'A') | |
index = int(request.args.get('index', 0)) | |
if set_name == 'A': | |
english = english_sentences_A[index] | |
japanese = translation_dict_A[english] | |
total = len(english_sentences_A) | |
elif set_name == 'B': | |
english = english_sentences_B[index] | |
japanese = translation_dict_B[english] | |
total = len(english_sentences_B) | |
elif set_name == 'C': | |
english = english_sentences_C[index] | |
japanese = translation_dict_C[english] | |
total = len(english_sentences_C) | |
elif set_name == 'D': | |
english = english_sentences_D[index] | |
japanese = translation_dict_D[english] | |
total = len(english_sentences_D) | |
elif set_name == 'F': | |
english = english_sentences_F[index] | |
japanese = translation_dict_F[english] | |
total = len(english_sentences_F) | |
elif set_name == 'G': | |
english = english_sentences_G[index] | |
japanese = translation_dict_G[english] | |
total = len(english_sentences_G) | |
audio_url = url_for('static', filename=f"audio/{english[:10].replace(' ', '_')}.mp3") | |
return render_template('index.html', set_name=set_name, index=index, english=english, japanese=japanese, total=total, audio_url=audio_url) | |
if __name__ == '__main__': | |
app.run(debug=True, host="0.0.0.0", port=7860) | |