Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,69 +1,134 @@
|
|
| 1 |
-
from flask import Flask, request, jsonify, render_template
|
| 2 |
import base64
|
| 3 |
import os
|
|
|
|
|
|
|
| 4 |
import string
|
| 5 |
import random
|
| 6 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
app = Flask(__name__)
|
| 9 |
|
| 10 |
-
#
|
| 11 |
@app.route('/')
|
| 12 |
@app.route('/index', methods=['GET', 'POST'])
|
| 13 |
def index():
|
| 14 |
return render_template('index.html')
|
| 15 |
|
| 16 |
-
#
|
| 17 |
@app.route('/feedback', methods=['GET', 'POST'])
|
| 18 |
def feedback():
|
| 19 |
-
return render_template(
|
| 20 |
|
| 21 |
-
#
|
| 22 |
@app.route('/talk_detail', methods=['GET', 'POST'])
|
| 23 |
def talk_detail():
|
| 24 |
-
return render_template(
|
| 25 |
|
| 26 |
-
#
|
| 27 |
@app.route('/upload_audio', methods=['POST'])
|
| 28 |
def upload_audio():
|
| 29 |
try:
|
| 30 |
data = request.get_json()
|
| 31 |
-
if not data:
|
| 32 |
-
return jsonify({"error": "
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
except Exception as decode_err:
|
| 42 |
-
return jsonify({"error": "Base64デコードに失敗しました", "details": str(decode_err)}), 400
|
| 43 |
-
|
| 44 |
-
# 書き込み用ディレクトリとして /tmp/data を使用(/tmp は書き込み可能)
|
| 45 |
-
persist_dir = "/tmp/data"
|
| 46 |
-
os.makedirs(persist_dir, exist_ok=True)
|
| 47 |
-
|
| 48 |
-
filepath = os.path.join(persist_dir, generate_filename(6)) # ここだけ変更しました
|
| 49 |
-
with open(filepath, 'wb') as f:
|
| 50 |
f.write(audio_binary)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
except Exception as e:
|
| 55 |
-
|
| 56 |
-
return jsonify({"error": "
|
| 57 |
-
|
| 58 |
-
def generate_random_string(length):
|
| 59 |
-
letters = string.ascii_letters + string.digits
|
| 60 |
-
return ''.join(random.choice(letters) for i in range(length))
|
| 61 |
-
|
| 62 |
-
def generate_filename(random_length):
|
| 63 |
-
random_string = generate_random_string(random_length)
|
| 64 |
-
current_time = datetime.now().strftime("%Y%m%d%H%M%S")
|
| 65 |
-
filename = f"{current_time}_{random_string}.wav"
|
| 66 |
-
return filename
|
| 67 |
|
| 68 |
if __name__ == '__main__':
|
| 69 |
port = int(os.environ.get("PORT", 7860))
|
|
|
|
| 1 |
+
from flask import Flask, request, jsonify, render_template, send_from_directory
|
| 2 |
import base64
|
| 3 |
import os
|
| 4 |
+
import shutil
|
| 5 |
+
import numpy as np
|
| 6 |
import string
|
| 7 |
import random
|
| 8 |
from datetime import datetime
|
| 9 |
+
from pyannote.audio import Model, Inference
|
| 10 |
+
from pydub import AudioSegment
|
| 11 |
+
|
| 12 |
+
# Hugging Face のトークン取得(環境変数 HF に設定)
|
| 13 |
+
hf_token = os.environ.get("HF")
|
| 14 |
+
if hf_token is None:
|
| 15 |
+
raise ValueError("HUGGINGFACE_HUB_TOKEN が設定されていません。")
|
| 16 |
+
|
| 17 |
+
# キャッシュディレクトリの作成(書き込み可能な /tmp を利用)
|
| 18 |
+
cache_dir = "/tmp/hf_cache"
|
| 19 |
+
os.makedirs(cache_dir, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
# pyannote モデルの読み込み
|
| 22 |
+
model = Model.from_pretrained("pyannote/embedding", use_auth_token=hf_token, cache_dir=cache_dir)
|
| 23 |
+
inference = Inference(model)
|
| 24 |
+
|
| 25 |
+
def cosine_similarity(vec1, vec2):
|
| 26 |
+
vec1 = vec1 / np.linalg.norm(vec1)
|
| 27 |
+
vec2 = vec2 / np.linalg.norm(vec2)
|
| 28 |
+
return np.dot(vec1, vec2)
|
| 29 |
+
|
| 30 |
+
def segment_audio(path, target_path='/tmp/setup_voice', seg_duration=1.0):
|
| 31 |
+
"""
|
| 32 |
+
音声を指定秒数ごとに分割する。
|
| 33 |
+
target_path に分割したファイルを保存し、元の音声の総長(ミリ秒)を返す。
|
| 34 |
+
"""
|
| 35 |
+
os.makedirs(target_path, exist_ok=True)
|
| 36 |
+
base_sound = AudioSegment.from_file(path)
|
| 37 |
+
duration_ms = len(base_sound)
|
| 38 |
+
seg_duration_ms = int(seg_duration * 1000)
|
| 39 |
+
|
| 40 |
+
for i, start in enumerate(range(0, duration_ms, seg_duration_ms)):
|
| 41 |
+
end = min(start + seg_duration_ms, duration_ms)
|
| 42 |
+
segment = base_sound[start:end]
|
| 43 |
+
segment.export(os.path.join(target_path, f'{i}.wav'), format="wav")
|
| 44 |
+
|
| 45 |
+
return target_path, duration_ms
|
| 46 |
+
|
| 47 |
+
def calculate_similarity(path1, path2):
|
| 48 |
+
embedding1 = inference(path1)
|
| 49 |
+
embedding2 = inference(path2)
|
| 50 |
+
return float(cosine_similarity(embedding1.data.flatten(), embedding2.data.flatten()))
|
| 51 |
+
|
| 52 |
+
def process_audio(reference_path, input_path, output_folder='/tmp/data/matched_segments', seg_duration=1.0, threshold=0.5):
|
| 53 |
+
"""
|
| 54 |
+
入力音声ファイルを seg_duration 秒ごとに分割し、各セグメントと参照音声の類似度を計算。
|
| 55 |
+
類似度が threshold を超えたセグメントを output_folder にコピーし、マッチした時間(ms)と
|
| 56 |
+
マッチしなかった時間(ms)を返す。
|
| 57 |
+
"""
|
| 58 |
+
os.makedirs(output_folder, exist_ok=True)
|
| 59 |
+
segmented_path, total_duration_ms = segment_audio(input_path, seg_duration=seg_duration)
|
| 60 |
+
|
| 61 |
+
matched_time_ms = 0
|
| 62 |
+
for file in sorted(os.listdir(segmented_path)):
|
| 63 |
+
segment_file = os.path.join(segmented_path, file)
|
| 64 |
+
similarity = calculate_similarity(segment_file, reference_path)
|
| 65 |
+
if similarity > threshold:
|
| 66 |
+
shutil.copy(segment_file, output_folder)
|
| 67 |
+
matched_time_ms += len(AudioSegment.from_file(segment_file))
|
| 68 |
+
|
| 69 |
+
unmatched_time_ms = total_duration_ms - matched_time_ms
|
| 70 |
+
return matched_time_ms, unmatched_time_ms
|
| 71 |
+
|
| 72 |
+
def generate_random_string(length):
|
| 73 |
+
letters = string.ascii_letters + string.digits
|
| 74 |
+
return ''.join(random.choice(letters) for i in range(length))
|
| 75 |
+
|
| 76 |
+
def generate_filename(random_length):
|
| 77 |
+
random_string = generate_random_string(random_length)
|
| 78 |
+
current_time = datetime.now().strftime("%Y%m%d%H%M%S")
|
| 79 |
+
filename = f"{current_time}_{random_string}.wav"
|
| 80 |
+
return filename
|
| 81 |
|
| 82 |
app = Flask(__name__)
|
| 83 |
|
| 84 |
+
# トップページ(テンプレート: index.html)
|
| 85 |
@app.route('/')
|
| 86 |
@app.route('/index', methods=['GET', 'POST'])
|
| 87 |
def index():
|
| 88 |
return render_template('index.html')
|
| 89 |
|
| 90 |
+
# フィードバック画面(テンプレート: feedback.html)
|
| 91 |
@app.route('/feedback', methods=['GET', 'POST'])
|
| 92 |
def feedback():
|
| 93 |
+
return render_template('feedback.html')
|
| 94 |
|
| 95 |
+
# 会話詳細画面(テンプレート: talkDetail.html)
|
| 96 |
@app.route('/talk_detail', methods=['GET', 'POST'])
|
| 97 |
def talk_detail():
|
| 98 |
+
return render_template('talkDetail.html')
|
| 99 |
|
| 100 |
+
# 音声アップロード&解析エンドポイント
|
| 101 |
@app.route('/upload_audio', methods=['POST'])
|
| 102 |
def upload_audio():
|
| 103 |
try:
|
| 104 |
data = request.get_json()
|
| 105 |
+
if not data or 'audio_data' not in data:
|
| 106 |
+
return jsonify({"error": "音声データがありません"}), 400
|
| 107 |
+
|
| 108 |
+
# Base64デコードして音声バイナリを取得
|
| 109 |
+
audio_binary = base64.b64decode(data['audio_data'])
|
| 110 |
+
audio_dir = "/tmp/data"
|
| 111 |
+
os.makedirs(audio_dir, exist_ok=True)
|
| 112 |
+
# 固定ファイル名(必要に応じて generate_filename() で一意のファイル名に変更可能)
|
| 113 |
+
audio_path = os.path.join(audio_dir, "recorded_audio.wav")
|
| 114 |
+
with open(audio_path, 'wb') as f:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
f.write(audio_binary)
|
| 116 |
+
|
| 117 |
+
# 参照音声ファイルのパスを指定(sample.wav を正しい場所に配置すること)
|
| 118 |
+
reference_audio = os.path.abspath('./sample.wav')
|
| 119 |
+
if not os.path.exists(reference_audio):
|
| 120 |
+
return jsonify({"error": "参照音声ファイルが見つかりません", "details": reference_audio}), 500
|
| 121 |
+
|
| 122 |
+
# 音声解析:参照音声とアップロードされた音声との類似度をセグメント毎に計算
|
| 123 |
+
# threshold の値は調整可能です(例: 0.1)
|
| 124 |
+
matched_time, unmatched_time = process_audio(reference_audio, audio_path, threshold=0.1)
|
| 125 |
+
total_time = matched_time + unmatched_time
|
| 126 |
+
rate = (matched_time / total_time) * 100 if total_time > 0 else 0
|
| 127 |
+
|
| 128 |
+
return jsonify({"rate": rate}), 200
|
| 129 |
except Exception as e:
|
| 130 |
+
print("Error in /upload_audio:", str(e))
|
| 131 |
+
return jsonify({"error": "サーバーエラー", "details": str(e)}), 500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
if __name__ == '__main__':
|
| 134 |
port = int(os.environ.get("PORT", 7860))
|