-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
251 lines (211 loc) · 8.93 KB
/
app.py
File metadata and controls
251 lines (211 loc) · 8.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import os
import logging
import threading
from pathlib import Path
from flask import Flask, render_template, request, jsonify, send_from_directory
from maincode.aichat import AIChat
from maincode.aiprompt import AIPrompt
from maincode.file import MusicLrcEditor
from maincode.lrclistutils import integrateLyrics, integrateLRC, splitLrcLines, buildLyricsIndex
from maincode.search import EnhancedLyricsProcessor, LyricsSearchResult
import traceback
from maincode.roma2kana import romaji2Hiragana
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Flask应用初始化
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024 # 最大上传文件大小:100MB
app.secret_key = 'lyrics_tool_2025'
# 创建上传目录
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# 支持的音频文件格式
SUPPORTED_FORMATS = (".mp3", ".opus", ".ogg", ".flac", ".wav", ".m4a")
# 全局存储处理状态和数据
processing_data = {
'current_file': "",
'status': '就绪',
'metadata': {},
'japanese_text': '',
'translation_text': '',
'phonetic_text': '',
'edit_text': '',
'edit_bak': ''
}
# 锁机制确保线程安全
data_lock = threading.Lock()
def process_file(file_path):
"""处理音频文件"""
with data_lock:
processing_data['current_file'] = file_path
file_name = Path(file_path).stem
processing_data['current_file_name'] = file_name
processing_data['status'] = f"正在处理文件: {file_name}"
# 启动歌词匹配线程
threading.Thread(target=match_lyrics_worker, args=(file_path,), daemon=True).start()
def match_lyrics_worker(file_path):
"""更新歌词匹配工作线程,使用实际搜索服务"""
try:
with data_lock:
processing_data['status'] = "正在匹配歌词..."
processor = EnhancedLyricsProcessor()
best_lyrics = processor.search_best_lyrics(file_path)
if isinstance(best_lyrics, LyricsSearchResult):
# print("匹配结果:", best_lyrics)
min_score = 70
if best_lyrics.score >= min_score and best_lyrics.raw:
parse_lyrics(best_lyrics)
else:
with data_lock:
processing_data['status'] = "未找到匹配的歌词"
else:
with data_lock:
processing_data['status'] = best_lyrics['message']
except Exception as e:
print(traceback.format_exc())
logging.error(f"匹配歌词失败: {e}")
with data_lock:
processing_data['status'] = f"匹配歌词失败: {str(e)}"
def parse_lyrics(lyrics_data):
"""解析歌词数据"""
with (data_lock):
_raw = lyrics_data.raw
if _raw:
lrc_lines = _raw.replace("\r\n", "\n").split("\n")
_, root, _ = splitLrcLines(lrc_lines)
processing_data['edit_text'] = buildLyricsIndex(root)
processing_data['edit_bak'] = processing_data['edit_text']
# 更新文本内容
processing_data['japanese_text'] = lyrics_data.raw
processing_data['translation_text'] = lyrics_data.translation
processing_data['phonetic_text'] = romaji2Hiragana(lyrics_data.transliteration)
# 填充编辑区域
processing_data['status'] = "歌词匹配完成"
def embed_lyrics_to_file(lrc_content):
"""嵌入歌词到音频文件"""
with data_lock:
if not processing_data['current_file']:
raise Exception("无当前处理文件")
file_path = processing_data['current_file']
try:
# 根据文件格式嵌入歌词
mle = MusicLrcEditor(file_path)
mle.lrc = lrc_content
mle.write_lyrics()
return True
except Exception as e:
print(traceback.format_exc())
raise Exception(f"嵌入歌词失败: {str(e)}")
# ------------------- Flask路由 -------------------
@app.route('/')
def index():
"""主页面"""
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_file():
"""文件上传接口"""
if 'file' not in request.files:
return jsonify({'status': 'error', 'message': '未选择文件'})
file = request.files['file']
# print("file.filename:", file.filename)
if file.filename == '':
return jsonify({'status': 'error', 'message': '文件名为空'})
if file and file.filename.lower().endswith(SUPPORTED_FORMATS):
file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(file_path)
# print("file_path:", file_path)
# 处理文件
threading.Thread(target=process_file, args=(file_path,), daemon=True).start()
return jsonify({
'status': 'success',
'filename': file.filename,
'message': '文件上传成功,开始处理'
})
else:
return jsonify({
'status': 'error',
'message': f'不支持的文件格式,支持格式:{", ".join(SUPPORTED_FORMATS)}'
})
@app.route('/status')
def get_status():
"""获取处理状态"""
with data_lock:
return jsonify({
'status': processing_data['status'],
'filename': os.path.basename(processing_data['current_file']) if processing_data['current_file'] else '',
'metadata': processing_data['metadata'],
'japanese_text': processing_data['japanese_text'],
'translation_text': processing_data['translation_text'],
'phonetic_text': processing_data['phonetic_text'],
'edit_text': processing_data['edit_text']
})
@app.route('/embed', methods=['POST'])
def embed_lyrics():
"""嵌入歌词接口"""
try:
# print(request.json)
edit_content = request.json.get('edit_content', '')
japanese_content = request.json.get('japanese_content', '')
translation_content = request.json.get('translation_content', '')
phonetic_content = request.json.get('phonetic_content', '')
ai_Select_content = request.json.get('ai_Select_content', '')
api_key_content = request.json.get('api_key_content', '')
seq1_content = request.json.get('seq1_content')
seq2_content = request.json.get('seq2_content')
seq3_content = request.json.get('seq3_content')
seq4_content = request.json.get('seq4_content')
sequence = []
_dict = {"jp": "japanese",
"kana": "phonetic",
"cn": "translation",
"roma": "hepburn",
"disable": "disable"}
for item in [seq1_content, seq2_content, seq3_content, seq4_content]:
if item != "disable":
sequence.append(_dict[item])
# sequence = ["japanese", "phonetic", "translation"]
if (ai_Select_content != "disable") and api_key_content:
if not phonetic_content:
if translation_content:
prompt = AIPrompt.SPSPrompt
else:
prompt = AIPrompt.SPTSPrompt
aichat = AIChat(api_key_content, ai_Select_content)
res_dict = aichat.call(edit_content, prompt, processing_data['current_file_name'])
edit_content = res_dict['reply']
with data_lock:
if not processing_data['current_file']:
return jsonify({'status': 'error', 'message': '请先上传文件并匹配歌词'})
# print("edit_content:", edit_content)
# print('edit_bak:', processing_data['edit_bak'])
prefix, root, invalid = integrateLyrics(japanese_content,
phonetic_content,
translation_content,
edit_content,
processing_data['edit_bak'])
if invalid:
print("无效行:")
for line in invalid:
print(line)
lrc_lines_list = integrateLRC(prefix, root, sequence)
# 嵌入歌词
embed_lyrics_to_file(lrc_lines_list)
with data_lock:
processing_data['status'] = "歌词已成功嵌入到音频文件"
return jsonify({
'status': 'success',
'message': '歌词已成功嵌入到音频文件',
'filename': os.path.basename(processing_data['current_file'])
})
except Exception as e:
print(traceback.format_exc())
logging.error(f"嵌入歌词失败: {e}")
with data_lock:
processing_data['status'] = f"处理失败: {str(e)}"
return jsonify({'status': 'error', 'message': str(e)})
@app.route('/download/<filename>')
def download_file(filename):
"""下载处理后的文件"""
return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)