generated from dellevin/template
555
This commit is contained in:
@@ -85,7 +85,9 @@
|
|||||||
"Bash(python -c \"import llama_cpp; print\\('file:', llama_cpp.__file__\\); print\\('supports_gpu:', llama_cpp.llama_supports_gpu_offload\\(\\)\\)\")",
|
"Bash(python -c \"import llama_cpp; print\\('file:', llama_cpp.__file__\\); print\\('supports_gpu:', llama_cpp.llama_supports_gpu_offload\\(\\)\\)\")",
|
||||||
"Bash(cat \"E:/AI/ai-translation/argos/translate-en_zh-1_9/metadata.json\")",
|
"Bash(cat \"E:/AI/ai-translation/argos/translate-en_zh-1_9/metadata.json\")",
|
||||||
"Bash(ls \"E:\\\\AI\\\\ai-translation\\\\argos\")",
|
"Bash(ls \"E:\\\\AI\\\\ai-translation\\\\argos\")",
|
||||||
"Bash(cat \"E:\\\\AI\\\\ai-translation\\\\nllb\\\\nllb-200-distilled-600M\\\\config.json\" 2>&1 | head -20)"
|
"Bash(cat \"E:\\\\AI\\\\ai-translation\\\\nllb\\\\nllb-200-distilled-600M\\\\config.json\" 2>&1 | head -20)",
|
||||||
|
"Bash(ls \"E:/AI/\" 2>/dev/null)",
|
||||||
|
"WebSearch"
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
整合工具集主入口
|
整合工具集主入口
|
||||||
只负责创建 Flask 应用、注册蓝图和启动服务
|
只负责创建 Flask 应用、注册蓝图和启动服务
|
||||||
@@ -11,7 +11,7 @@ from datetime import datetime
|
|||||||
from flask import Flask, render_template, jsonify, g, request, session, redirect
|
from flask import Flask, render_template, jsonify, g, request, session, redirect
|
||||||
|
|
||||||
from config import PORT, LOGIN_ENABLED, LOGIN_USERNAME, LOGIN_PASSWORD, SECRET_KEY
|
from config import PORT, LOGIN_ENABLED, LOGIN_USERNAME, LOGIN_PASSWORD, SECRET_KEY
|
||||||
from blueprints import pin_tu_bp, base64_bp, down_video_bp, fen_ci_bp, content_tag_bp, chmod_calc_bp, json_format_bp, qr_code_bp, http_status_bp, url_parser_bp, token_gen_bp, sovits_tts_bp, stt_bp, ai_dubbing_bp, rvc_bp, audio_slicer_bp, uvr_sep_bp, mp4_to_audio_bp, ai_translate_bp
|
from blueprints import pin_tu_bp, base64_bp, down_video_bp, fen_ci_bp, content_tag_bp, chmod_calc_bp, json_format_bp, qr_code_bp, http_status_bp, url_parser_bp, token_gen_bp, sovits_tts_bp, stt_bp, ai_dubbing_bp, rvc_bp, audio_slicer_bp, uvr_sep_bp, mp4_to_audio_bp
|
||||||
from utils.stats_db import init_db, record_call, get_total_count, get_avg_duration, get_daily_counts, get_monthly_counts, get_available_years, get_available_months, get_daily_counts_by_month, get_hourly_counts, get_endpoint_stats, get_today_count, get_yesterday_count, get_month_count, get_success_rate, get_duration_distribution, get_slowest_endpoints, get_week_compare, get_recent_calls, get_active_days
|
from utils.stats_db import init_db, record_call, get_total_count, get_avg_duration, get_daily_counts, get_monthly_counts, get_available_years, get_available_months, get_daily_counts_by_month, get_hourly_counts, get_endpoint_stats, get_today_count, get_yesterday_count, get_month_count, get_success_rate, get_duration_distribution, get_slowest_endpoints, get_week_compare, get_recent_calls, get_active_days
|
||||||
from utils.stats_db import ALLOWED_TABLES, get_table_info, get_table_rows, get_table_count, insert_row, update_row, delete_rows, clear_table
|
from utils.stats_db import ALLOWED_TABLES, get_table_info, get_table_rows, get_table_count, insert_row, update_row, delete_rows, clear_table
|
||||||
|
|
||||||
@@ -248,23 +248,12 @@ def create_app():
|
|||||||
app.register_blueprint(audio_slicer_bp)
|
app.register_blueprint(audio_slicer_bp)
|
||||||
app.register_blueprint(uvr_sep_bp)
|
app.register_blueprint(uvr_sep_bp)
|
||||||
app.register_blueprint(mp4_to_audio_bp)
|
app.register_blueprint(mp4_to_audio_bp)
|
||||||
app.register_blueprint(ai_translate_bp)
|
|
||||||
|
|
||||||
return app
|
return app
|
||||||
|
|
||||||
app = create_app()
|
app = create_app()
|
||||||
|
|
||||||
|
|
||||||
def start_flask():
|
|
||||||
"""供桌面启动器调用,以非调试模式运行 Flask"""
|
|
||||||
from config import AUTO_OPEN_BROWSER
|
|
||||||
if AUTO_OPEN_BROWSER:
|
|
||||||
import webbrowser
|
|
||||||
import threading as _t
|
|
||||||
_t.Timer(1, webbrowser.open, args=[f'http://127.0.0.1:{PORT}']).start()
|
|
||||||
a = create_app()
|
|
||||||
a.run(host='127.0.0.1', port=PORT, use_reloader=False, threaded=True)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
from config import AUTO_OPEN_BROWSER
|
from config import AUTO_OPEN_BROWSER
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# blueprints package
|
# blueprints package
|
||||||
from .pin_tu import bp as pin_tu_bp
|
from .pin_tu import bp as pin_tu_bp
|
||||||
from .base64_codec import bp as base64_bp
|
from .base64_codec import bp as base64_bp
|
||||||
from .down_video import bp as down_video_bp
|
from .down_video import bp as down_video_bp
|
||||||
@@ -17,10 +17,9 @@ from .rvc import bp as rvc_bp
|
|||||||
from .audio_slicer import bp as audio_slicer_bp
|
from .audio_slicer import bp as audio_slicer_bp
|
||||||
from .uvr_sep import bp as uvr_sep_bp
|
from .uvr_sep import bp as uvr_sep_bp
|
||||||
from .mp4_to_audio import bp as mp4_to_audio_bp
|
from .mp4_to_audio import bp as mp4_to_audio_bp
|
||||||
from .ai_translate import bp as ai_translate_bp
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
'pin_tu_bp', 'base64_bp', 'down_video_bp', 'fen_ci_bp', 'content_tag_bp',
|
'pin_tu_bp', 'base64_bp', 'down_video_bp', 'fen_ci_bp', 'content_tag_bp',
|
||||||
'chmod_calc_bp', 'json_format_bp', 'qr_code_bp', 'http_status_bp', 'url_parser_bp', 'token_gen_bp',
|
'chmod_calc_bp', 'json_format_bp', 'qr_code_bp', 'http_status_bp', 'url_parser_bp', 'token_gen_bp',
|
||||||
'sovits_tts_bp', 'stt_bp', 'ai_dubbing_bp', 'rvc_bp', 'audio_slicer_bp', 'uvr_sep_bp', 'mp4_to_audio_bp', 'ai_translate_bp',
|
'sovits_tts_bp', 'stt_bp', 'ai_dubbing_bp', 'rvc_bp', 'audio_slicer_bp', 'uvr_sep_bp', 'mp4_to_audio_bp',
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -1,621 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
ai-translate AI 翻译蓝图
|
|
||||||
支持 NLLB-200 本地翻译引擎
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import json
|
|
||||||
import uuid
|
|
||||||
import threading
|
|
||||||
import tempfile
|
|
||||||
from flask import Blueprint, render_template, request, jsonify, send_file
|
|
||||||
|
|
||||||
bp = Blueprint('ai_translate', __name__, url_prefix='/ai-translate')
|
|
||||||
|
|
||||||
try:
|
|
||||||
from config import BASE_DIR
|
|
||||||
except ImportError:
|
|
||||||
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
|
||||||
CONFIG_PATH = os.path.join(BASE_DIR, 'config', 'ai_translate_config.json')
|
|
||||||
|
|
||||||
# 引擎状态
|
|
||||||
_model = None
|
|
||||||
_model_lock = threading.Lock()
|
|
||||||
_engine_status = {'loaded': False, 'loading': False, 'engine_type': None, 'model_name': None, 'error': None}
|
|
||||||
|
|
||||||
_tasks = {}
|
|
||||||
|
|
||||||
SUBTITLE_EXTS = ('.srt', '.ass', '.ssa', '.vtt')
|
|
||||||
LANGUAGES = {
|
|
||||||
'zh': '中文', 'en': '英文', 'ja': '日文', 'ko': '韩文',
|
|
||||||
'fr': '法文', 'de': '德文', 'es': '西班牙文', 'ru': '俄文',
|
|
||||||
'th': '泰文', 'vi': '越南文', 'it': '意大利文',
|
|
||||||
'pt': '葡萄牙文', 'auto': '自动检测',
|
|
||||||
}
|
|
||||||
|
|
||||||
# NLLB-200 语言代码映射
|
|
||||||
_NLLB_LANG_MAP = {
|
|
||||||
'zh': 'zho_Hans', 'en': 'eng_Latn', 'ja': 'jpn_Jpan', 'ko': 'kor_Hang',
|
|
||||||
'fr': 'fra_Latn', 'de': 'deu_Latn', 'es': 'spa_Latn', 'ru': 'rus_Cyrl',
|
|
||||||
'th': 'tha_Thai', 'vi': 'vie_Latn', 'it': 'ita_Latn',
|
|
||||||
'pt': 'por_Latn',
|
|
||||||
}
|
|
||||||
|
|
||||||
# langdetect 返回值 → 我们的语言代码
|
|
||||||
_DETECT_LANG_MAP = {
|
|
||||||
'zh-cn': 'zh', 'zh-tw': 'zh', 'zh': 'zh',
|
|
||||||
'en': 'en', 'ja': 'ja', 'ko': 'ko',
|
|
||||||
'fr': 'fr', 'de': 'de', 'es': 'es', 'ru': 'ru',
|
|
||||||
'th': 'th', 'vi': 'vi', 'it': 'it', 'pt': 'pt',
|
|
||||||
}
|
|
||||||
|
|
||||||
ENGINE_TYPES = {
|
|
||||||
'nllb': {'name': 'NLLB-200', 'desc': 'HF 目录或模型 ID'},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _default_config():
|
|
||||||
return {
|
|
||||||
'engine_type': 'nllb',
|
|
||||||
'nllb_dir': '',
|
|
||||||
'max_new_tokens': 512,
|
|
||||||
'batch_size': 8,
|
|
||||||
'last_nllb_model': '',
|
|
||||||
'last_src_lang': 'en',
|
|
||||||
'last_tgt_lang': 'zh',
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _load_config():
|
|
||||||
cfg = _default_config()
|
|
||||||
if os.path.exists(CONFIG_PATH):
|
|
||||||
try:
|
|
||||||
with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
|
|
||||||
cfg.update(json.load(f))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return cfg
|
|
||||||
|
|
||||||
|
|
||||||
def _save_config(cfg):
|
|
||||||
os.makedirs(os.path.dirname(CONFIG_PATH), exist_ok=True)
|
|
||||||
with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
|
|
||||||
json.dump(cfg, f, ensure_ascii=False, indent=2)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 字幕解析 ====================
|
|
||||||
|
|
||||||
def _parse_srt(text):
|
|
||||||
blocks = re.split(r'\n\s*\n', text.strip())
|
|
||||||
entries = []
|
|
||||||
for block in blocks:
|
|
||||||
lines = block.strip().split('\n')
|
|
||||||
if len(lines) < 3:
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
idx = int(lines[0].strip())
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
timecode = lines[1].strip()
|
|
||||||
content = '\n'.join(lines[2:]).strip()
|
|
||||||
if content:
|
|
||||||
entries.append((idx, timecode, content))
|
|
||||||
return entries
|
|
||||||
|
|
||||||
|
|
||||||
def _build_srt(entries):
|
|
||||||
parts = []
|
|
||||||
for idx, tc, content in entries:
|
|
||||||
parts.append(f'{idx}\n{tc}\n{content}')
|
|
||||||
return '\n\n'.join(parts) + '\n'
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_vtt(text):
|
|
||||||
text = re.sub(r'^WEBVTT\s*\n', '', text.strip(), count=1)
|
|
||||||
blocks = re.split(r'\n\s*\n', text.strip())
|
|
||||||
entries = []
|
|
||||||
for i, block in enumerate(blocks):
|
|
||||||
lines = block.strip().split('\n')
|
|
||||||
if len(lines) < 2:
|
|
||||||
continue
|
|
||||||
timecode = None
|
|
||||||
content_lines = []
|
|
||||||
for line in lines:
|
|
||||||
if '-->' in line:
|
|
||||||
timecode = line.strip()
|
|
||||||
elif timecode is not None:
|
|
||||||
content_lines.append(line)
|
|
||||||
else:
|
|
||||||
if '-->' not in line:
|
|
||||||
continue
|
|
||||||
if timecode and content_lines:
|
|
||||||
entries.append((i + 1, timecode, '\n'.join(content_lines).strip()))
|
|
||||||
return entries
|
|
||||||
|
|
||||||
|
|
||||||
def _build_vtt(entries):
|
|
||||||
parts = ['WEBVTT\n']
|
|
||||||
for idx, tc, content in entries:
|
|
||||||
parts.append(f'{idx}\n{tc}\n{content}')
|
|
||||||
return '\n\n'.join(parts) + '\n'
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_ass(text):
|
|
||||||
entries = []
|
|
||||||
for line in text.split('\n'):
|
|
||||||
line = line.strip()
|
|
||||||
if line.lower().startswith('dialogue:'):
|
|
||||||
entries.append(line)
|
|
||||||
return entries
|
|
||||||
|
|
||||||
|
|
||||||
def _ass_extract_text(dialogue_line):
|
|
||||||
parts = dialogue_line.split(',', 9)
|
|
||||||
if len(parts) < 10:
|
|
||||||
return dialogue_line, ''
|
|
||||||
text = parts[9]
|
|
||||||
text = re.sub(r'\{[^}]*\}', '', text)
|
|
||||||
text = text.replace('\\N', '\n').replace('\\n', '\n')
|
|
||||||
return dialogue_line, text.strip()
|
|
||||||
|
|
||||||
|
|
||||||
def _ass_replace_text(dialogue_line, new_text):
|
|
||||||
parts = dialogue_line.split(',', 9)
|
|
||||||
if len(parts) < 10:
|
|
||||||
return dialogue_line
|
|
||||||
translated = new_text.replace('\n', '\\N')
|
|
||||||
parts[9] = translated
|
|
||||||
return ','.join(parts)
|
|
||||||
|
|
||||||
|
|
||||||
def _build_ass(original_lines, translated_texts):
|
|
||||||
result = []
|
|
||||||
trans_idx = 0
|
|
||||||
for line in original_lines:
|
|
||||||
if line.lower().startswith('dialogue:'):
|
|
||||||
if trans_idx < len(translated_texts):
|
|
||||||
result.append(_ass_replace_text(line, translated_texts[trans_idx]))
|
|
||||||
trans_idx += 1
|
|
||||||
else:
|
|
||||||
result.append(line)
|
|
||||||
else:
|
|
||||||
result.append(line)
|
|
||||||
return '\n'.join(result)
|
|
||||||
|
|
||||||
|
|
||||||
def _detect_subtitle_format(filename, content):
|
|
||||||
ext = os.path.splitext(filename)[1].lower()
|
|
||||||
if ext == '.srt':
|
|
||||||
return 'srt'
|
|
||||||
if ext == '.vtt':
|
|
||||||
return 'vtt'
|
|
||||||
if ext in ('.ass', '.ssa'):
|
|
||||||
return 'ass'
|
|
||||||
if 'WEBVTT' in content[:20]:
|
|
||||||
return 'vtt'
|
|
||||||
if 'Dialogue:' in content:
|
|
||||||
return 'ass'
|
|
||||||
return 'srt'
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 模型加载与翻译 ====================
|
|
||||||
|
|
||||||
def _load_model(model_path, model_name):
|
|
||||||
global _model
|
|
||||||
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
|
||||||
import torch
|
|
||||||
|
|
||||||
_engine_status['loading'] = True
|
|
||||||
_engine_status['error'] = None
|
|
||||||
try:
|
|
||||||
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
|
||||||
tokenizer = AutoTokenizer.from_pretrained(model_path, clean_up_tokenization_spaces=True)
|
|
||||||
model = AutoModelForSeq2SeqLM.from_pretrained(model_path)
|
|
||||||
model = model.to(device)
|
|
||||||
model.eval()
|
|
||||||
_model = {'model': model, 'tokenizer': tokenizer, 'device': device}
|
|
||||||
|
|
||||||
_engine_status['loaded'] = True
|
|
||||||
_engine_status['model_name'] = model_name
|
|
||||||
_engine_status['engine_type'] = 'nllb'
|
|
||||||
_engine_status['error'] = None
|
|
||||||
return True, None
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
_engine_status['error'] = str(e)
|
|
||||||
return False, str(e)
|
|
||||||
finally:
|
|
||||||
_engine_status['loading'] = False
|
|
||||||
|
|
||||||
|
|
||||||
def _unload_model():
|
|
||||||
global _model
|
|
||||||
_model = None
|
|
||||||
_engine_status['loaded'] = False
|
|
||||||
_engine_status['model_name'] = None
|
|
||||||
_engine_status['engine_type'] = None
|
|
||||||
import gc
|
|
||||||
gc.collect()
|
|
||||||
try:
|
|
||||||
import torch
|
|
||||||
if torch.cuda.is_available():
|
|
||||||
torch.cuda.empty_cache()
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def _detect_lang(text):
|
|
||||||
"""用 langdetect 检测语言,返回我们的语言代码(如 'zh'、'en')"""
|
|
||||||
try:
|
|
||||||
from langdetect import detect
|
|
||||||
code = detect(text)
|
|
||||||
return _DETECT_LANG_MAP.get(code, _DETECT_LANG_MAP.get(code.split('-')[0], 'en'))
|
|
||||||
except Exception:
|
|
||||||
return 'en'
|
|
||||||
|
|
||||||
|
|
||||||
def _do_translate(texts, src_lang, tgt_lang, cfg):
|
|
||||||
if not _model:
|
|
||||||
return None, '模型未加载'
|
|
||||||
try:
|
|
||||||
import torch
|
|
||||||
model = _model['model']
|
|
||||||
tokenizer = _model['tokenizer']
|
|
||||||
device = _model['device']
|
|
||||||
|
|
||||||
nllb_tgt = _NLLB_LANG_MAP.get(tgt_lang, _NLLB_LANG_MAP.get('zh', 'zho_Hans'))
|
|
||||||
tgt_token_id = tokenizer.convert_tokens_to_ids(nllb_tgt)
|
|
||||||
|
|
||||||
# 自动检测时,用第一条文本检测语言
|
|
||||||
if src_lang == 'auto':
|
|
||||||
sample = ' '.join(texts[:3])
|
|
||||||
detected = _detect_lang(sample)
|
|
||||||
nllb_src = _NLLB_LANG_MAP.get(detected, 'eng_Latn')
|
|
||||||
else:
|
|
||||||
nllb_src = _NLLB_LANG_MAP.get(src_lang, 'eng_Latn')
|
|
||||||
|
|
||||||
results = []
|
|
||||||
for text in texts:
|
|
||||||
tokenizer.src_lang = nllb_src
|
|
||||||
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=512).to(device)
|
|
||||||
with torch.no_grad():
|
|
||||||
translated = model.generate(
|
|
||||||
**inputs,
|
|
||||||
forced_bos_token_id=tgt_token_id,
|
|
||||||
max_new_tokens=cfg.get('max_new_tokens', 512)
|
|
||||||
)
|
|
||||||
result = tokenizer.decode(translated[0], skip_special_tokens=True)
|
|
||||||
results.append(result)
|
|
||||||
return results, None
|
|
||||||
except Exception as e:
|
|
||||||
return None, str(e)
|
|
||||||
|
|
||||||
|
|
||||||
def _ensure_model(src_lang=None, tgt_lang=None):
|
|
||||||
if _engine_status['loaded'] and _model:
|
|
||||||
return True, None
|
|
||||||
cfg = _load_config()
|
|
||||||
models_dir = cfg.get('nllb_dir', '')
|
|
||||||
if not models_dir or not os.path.isdir(models_dir):
|
|
||||||
return False, '请在设置中配置 NLLB 模型目录'
|
|
||||||
|
|
||||||
# 用 last 模型或第一个可用
|
|
||||||
model_name = cfg.get('last_nllb_model', '')
|
|
||||||
if model_name:
|
|
||||||
full = os.path.join(models_dir, model_name)
|
|
||||||
if not (os.path.isdir(full) and os.path.exists(os.path.join(full, 'config.json'))):
|
|
||||||
model_name = ''
|
|
||||||
if not model_name:
|
|
||||||
for name in sorted(os.listdir(models_dir)):
|
|
||||||
full = os.path.join(models_dir, name)
|
|
||||||
if os.path.isdir(full) and os.path.exists(os.path.join(full, 'config.json')):
|
|
||||||
model_name = name
|
|
||||||
break
|
|
||||||
if not model_name:
|
|
||||||
return False, '未找到 NLLB 模型,请在设置中配置目录'
|
|
||||||
|
|
||||||
model_path = os.path.join(models_dir, model_name)
|
|
||||||
with _model_lock:
|
|
||||||
if _engine_status['loaded'] and _model:
|
|
||||||
return True, None
|
|
||||||
ok, load_err = _load_model(model_path, model_name)
|
|
||||||
if ok:
|
|
||||||
cfg['last_nllb_model'] = model_name
|
|
||||||
_save_config(cfg)
|
|
||||||
return ok, load_err
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 启动时自动加载模型 ====================
|
|
||||||
|
|
||||||
_auto_load_done = False
|
|
||||||
|
|
||||||
|
|
||||||
def _trigger_auto_load():
|
|
||||||
global _auto_load_done
|
|
||||||
if _auto_load_done:
|
|
||||||
return
|
|
||||||
_auto_load_done = True
|
|
||||||
|
|
||||||
threading.Thread(target=_ensure_model, daemon=True).start()
|
|
||||||
|
|
||||||
|
|
||||||
# ==================== 路由 ====================
|
|
||||||
|
|
||||||
@bp.route('/')
|
|
||||||
def page():
|
|
||||||
_trigger_auto_load()
|
|
||||||
cfg = _load_config()
|
|
||||||
return render_template('ai_translate.html', config=cfg, languages=LANGUAGES, engine_types=ENGINE_TYPES)
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/model-status')
|
|
||||||
def model_status():
|
|
||||||
return jsonify({
|
|
||||||
'loaded': _engine_status['loaded'],
|
|
||||||
'loading': _engine_status['loading'],
|
|
||||||
'model_name': _engine_status.get('model_name'),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/config', methods=['GET'])
|
|
||||||
def get_config():
|
|
||||||
return jsonify(_load_config())
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/config', methods=['POST'])
|
|
||||||
def save_config():
|
|
||||||
data = request.get_json()
|
|
||||||
cfg = _load_config()
|
|
||||||
for key in ('nllb_dir', 'last_src_lang', 'last_tgt_lang', 'max_new_tokens', 'batch_size'):
|
|
||||||
if key in data:
|
|
||||||
cfg[key] = data[key]
|
|
||||||
_save_config(cfg)
|
|
||||||
return jsonify({'success': True})
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/models')
|
|
||||||
def list_models():
|
|
||||||
cfg = _load_config()
|
|
||||||
models_dir = cfg.get('nllb_dir', '')
|
|
||||||
models = []
|
|
||||||
if models_dir and os.path.isdir(models_dir):
|
|
||||||
for name in sorted(os.listdir(models_dir)):
|
|
||||||
full = os.path.join(models_dir, name)
|
|
||||||
if os.path.isdir(full) and os.path.exists(os.path.join(full, 'config.json')):
|
|
||||||
models.append({'name': name, 'type': 'huggingface', 'path': full})
|
|
||||||
return jsonify({'models': models, 'models_dir': models_dir, 'last_model': cfg.get('last_nllb_model', '')})
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/languages')
|
|
||||||
def list_languages():
|
|
||||||
langs = [{'code': c, 'name': n} for c, n in LANGUAGES.items() if c != 'auto']
|
|
||||||
return jsonify({'src_langs': [{'code': 'auto', 'name': '自动检测'}] + langs, 'tgt_langs': langs})
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/unload-model', methods=['POST'])
|
|
||||||
def unload_model():
|
|
||||||
with _model_lock:
|
|
||||||
_unload_model()
|
|
||||||
cfg = _load_config()
|
|
||||||
cfg['last_nllb_model'] = ''
|
|
||||||
_save_config(cfg)
|
|
||||||
return jsonify({'success': True, 'message': '模型已卸载'})
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/load-model', methods=['POST'])
|
|
||||||
def load_model():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
model_name = data.get('model_name', '').strip()
|
|
||||||
if not model_name:
|
|
||||||
return jsonify({'success': False, 'error': '请指定模型名称'}), 400
|
|
||||||
|
|
||||||
cfg = _load_config()
|
|
||||||
models_dir = cfg.get('nllb_dir', '')
|
|
||||||
if not models_dir or not os.path.isdir(models_dir):
|
|
||||||
return jsonify({'success': False, 'error': '请先配置 NLLB 模型目录'}), 400
|
|
||||||
|
|
||||||
model_path = os.path.join(models_dir, model_name)
|
|
||||||
if not os.path.isdir(model_path):
|
|
||||||
return jsonify({'success': False, 'error': f'模型目录不存在: {model_name}'}), 400
|
|
||||||
|
|
||||||
with _model_lock:
|
|
||||||
_unload_model()
|
|
||||||
ok, err = _load_model(model_path, model_name)
|
|
||||||
if ok:
|
|
||||||
cfg['last_nllb_model'] = model_name
|
|
||||||
_save_config(cfg)
|
|
||||||
return jsonify({'success': True, 'model_name': model_name})
|
|
||||||
return jsonify({'success': False, 'error': err or '加载失败'}), 400
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/translate-text', methods=['POST'])
|
|
||||||
def translate_text():
|
|
||||||
data = request.get_json()
|
|
||||||
text = (data.get('text') or '').strip()
|
|
||||||
if not text:
|
|
||||||
return jsonify({'success': False, 'error': '请输入要翻译的文本'}), 400
|
|
||||||
|
|
||||||
src_lang = data.get('src_lang', 'en')
|
|
||||||
tgt_lang = data.get('tgt_lang', 'zh')
|
|
||||||
cfg = _load_config()
|
|
||||||
batch_size = cfg.get('batch_size', 8)
|
|
||||||
|
|
||||||
cfg['last_src_lang'] = src_lang
|
|
||||||
cfg['last_tgt_lang'] = tgt_lang
|
|
||||||
_save_config(cfg)
|
|
||||||
|
|
||||||
ok, err = _ensure_model(src_lang, tgt_lang)
|
|
||||||
if not ok:
|
|
||||||
return jsonify({'success': False, 'error': err}), 400
|
|
||||||
|
|
||||||
task_id = uuid.uuid4().hex
|
|
||||||
_tasks[task_id] = {'status': 'translating', 'progress': 0, 'result': None, 'error': None}
|
|
||||||
|
|
||||||
def _do_task():
|
|
||||||
try:
|
|
||||||
paragraphs = [p.strip() for p in text.split('\n') if p.strip()]
|
|
||||||
if not paragraphs:
|
|
||||||
paragraphs = [text]
|
|
||||||
|
|
||||||
all_results = []
|
|
||||||
total = len(paragraphs)
|
|
||||||
for i in range(0, total, batch_size):
|
|
||||||
batch = paragraphs[i:i + batch_size]
|
|
||||||
results, err = _do_translate(batch, src_lang, tgt_lang, cfg)
|
|
||||||
if err:
|
|
||||||
_tasks[task_id] = {'status': 'error', 'error': err}
|
|
||||||
return
|
|
||||||
all_results.extend(results)
|
|
||||||
_tasks[task_id]['progress'] = round((i + len(batch)) / total * 100)
|
|
||||||
|
|
||||||
_tasks[task_id] = {'status': 'done', 'result': '\n'.join(all_results), 'progress': 100}
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
_tasks[task_id] = {'status': 'error', 'error': str(e)}
|
|
||||||
|
|
||||||
threading.Thread(target=_do_task, daemon=True).start()
|
|
||||||
return jsonify({'success': True, 'task_id': task_id})
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/translate-file', methods=['POST'])
|
|
||||||
def translate_file():
|
|
||||||
if 'subtitle' not in request.files:
|
|
||||||
return jsonify({'success': False, 'error': '请上传字幕文件'}), 400
|
|
||||||
f = request.files['subtitle']
|
|
||||||
if not f.filename:
|
|
||||||
return jsonify({'success': False, 'error': '请上传字幕文件'}), 400
|
|
||||||
|
|
||||||
ext = os.path.splitext(f.filename)[1].lower()
|
|
||||||
if ext not in SUBTITLE_EXTS:
|
|
||||||
return jsonify({'success': False, 'error': f'不支持的格式: {ext},支持 SRT/ASS/VTT'}), 400
|
|
||||||
|
|
||||||
src_lang = request.form.get('src_lang', 'en')
|
|
||||||
tgt_lang = request.form.get('tgt_lang', 'zh')
|
|
||||||
cfg = _load_config()
|
|
||||||
batch_size = cfg.get('batch_size', 8)
|
|
||||||
|
|
||||||
cfg['last_src_lang'] = src_lang
|
|
||||||
cfg['last_tgt_lang'] = tgt_lang
|
|
||||||
_save_config(cfg)
|
|
||||||
|
|
||||||
ok, err = _ensure_model(src_lang, tgt_lang)
|
|
||||||
if not ok:
|
|
||||||
return jsonify({'success': False, 'error': err}), 400
|
|
||||||
|
|
||||||
content = f.read().decode('utf-8', errors='replace')
|
|
||||||
fmt = _detect_subtitle_format(f.filename, content)
|
|
||||||
|
|
||||||
task_id = uuid.uuid4().hex
|
|
||||||
_tasks[task_id] = {'status': 'translating', 'progress': 0, 'result': None, 'error': None,
|
|
||||||
'filename': f.filename, 'format': fmt}
|
|
||||||
|
|
||||||
def _do_task():
|
|
||||||
try:
|
|
||||||
if fmt == 'srt':
|
|
||||||
entries = _parse_srt(content)
|
|
||||||
texts = [e[2] for e in entries]
|
|
||||||
elif fmt == 'vtt':
|
|
||||||
entries = _parse_vtt(content)
|
|
||||||
texts = [e[2] for e in entries]
|
|
||||||
elif fmt == 'ass':
|
|
||||||
full_lines = content.split('\n')
|
|
||||||
dialogue_lines = [l for l in full_lines if l.strip().lower().startswith('dialogue:')]
|
|
||||||
texts = []
|
|
||||||
for dl in dialogue_lines:
|
|
||||||
_, txt = _ass_extract_text(dl)
|
|
||||||
texts.append(txt if txt else '')
|
|
||||||
entries = dialogue_lines
|
|
||||||
else:
|
|
||||||
_tasks[task_id] = {'status': 'error', 'error': '未知字幕格式'}
|
|
||||||
return
|
|
||||||
|
|
||||||
if not texts:
|
|
||||||
_tasks[task_id] = {'status': 'error', 'error': '字幕文件中未找到可翻译的文本'}
|
|
||||||
return
|
|
||||||
|
|
||||||
all_results = []
|
|
||||||
total = len(texts)
|
|
||||||
|
|
||||||
for i in range(0, total, batch_size):
|
|
||||||
batch = texts[i:i + batch_size]
|
|
||||||
batch = [t for t in batch if t.strip()]
|
|
||||||
if not batch:
|
|
||||||
all_results.extend(texts[i:i + batch_size])
|
|
||||||
_tasks[task_id]['progress'] = round((i + batch_size) / total * 100)
|
|
||||||
continue
|
|
||||||
|
|
||||||
results, err = _do_translate(batch, src_lang, tgt_lang, cfg)
|
|
||||||
if err:
|
|
||||||
_tasks[task_id] = {'status': 'error', 'error': err}
|
|
||||||
return
|
|
||||||
|
|
||||||
ri = 0
|
|
||||||
for j in range(i, min(i + batch_size, total)):
|
|
||||||
if texts[j].strip():
|
|
||||||
all_results.append(results[ri] if ri < len(results) else texts[j])
|
|
||||||
ri += 1
|
|
||||||
else:
|
|
||||||
all_results.append('')
|
|
||||||
_tasks[task_id]['progress'] = round(min(i + batch_size, total) / total * 100)
|
|
||||||
|
|
||||||
if fmt == 'srt':
|
|
||||||
translated_entries = [(entries[i][0], entries[i][1], all_results[i]) for i in range(len(entries))]
|
|
||||||
output = _build_srt(translated_entries)
|
|
||||||
elif fmt == 'vtt':
|
|
||||||
translated_entries = [(entries[i][0], entries[i][1], all_results[i]) for i in range(len(entries))]
|
|
||||||
output = _build_vtt(translated_entries)
|
|
||||||
elif fmt == 'ass':
|
|
||||||
output = _build_ass(content.split('\n'), all_results)
|
|
||||||
else:
|
|
||||||
output = '\n'.join(all_results)
|
|
||||||
|
|
||||||
out_path = os.path.join(tempfile.gettempdir(), f'ai_trans_{task_id}{ext}')
|
|
||||||
with open(out_path, 'w', encoding='utf-8') as fout:
|
|
||||||
fout.write(output)
|
|
||||||
|
|
||||||
_tasks[task_id] = {
|
|
||||||
'status': 'done', 'progress': 100,
|
|
||||||
'result': output, 'file_path': out_path,
|
|
||||||
'filename': f.filename, 'format': fmt,
|
|
||||||
}
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
_tasks[task_id] = {'status': 'error', 'error': str(e)}
|
|
||||||
|
|
||||||
threading.Thread(target=_do_task, daemon=True).start()
|
|
||||||
return jsonify({'success': True, 'task_id': task_id})
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/task-status/<task_id>')
|
|
||||||
def task_status(task_id):
|
|
||||||
task = _tasks.get(task_id)
|
|
||||||
if not task:
|
|
||||||
return jsonify({'success': False, 'error': '任务不存在'}), 404
|
|
||||||
return jsonify({'success': True, **task})
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/download/<task_id>')
|
|
||||||
def download(task_id):
|
|
||||||
task = _tasks.get(task_id)
|
|
||||||
if not task or task.get('status') != 'done':
|
|
||||||
return jsonify({'error': '文件不存在'}), 404
|
|
||||||
file_path = task.get('file_path')
|
|
||||||
if not file_path or not os.path.exists(file_path):
|
|
||||||
return jsonify({'error': '文件不存在'}), 404
|
|
||||||
orig = task.get('filename', 'translated')
|
|
||||||
base, ext = os.path.splitext(orig)
|
|
||||||
return send_file(file_path, as_attachment=True, download_name=f'{base}_translated{ext}')
|
|
||||||
|
|
||||||
|
|
||||||
@bp.route('/cleanup/<task_id>', methods=['POST'])
|
|
||||||
def cleanup(task_id):
|
|
||||||
task = _tasks.pop(task_id, None)
|
|
||||||
if task and task.get('file_path'):
|
|
||||||
try:
|
|
||||||
os.remove(task['file_path'])
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
return jsonify({'success': True})
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
{
|
|
||||||
"engine_type": "nllb",
|
|
||||||
"nllb_dir": "E:\\AI\\ai-translation\\nllb",
|
|
||||||
"max_new_tokens": 512,
|
|
||||||
"batch_size": 8,
|
|
||||||
"last_nllb_model": "nllb-200-distilled-1.3B",
|
|
||||||
"last_src_lang": "auto",
|
|
||||||
"last_tgt_lang": "zh"
|
|
||||||
}
|
|
||||||
5
flask-dev-api/config/mp4_to_audio_config.json
Normal file
5
flask-dev-api/config/mp4_to_audio_config.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"output_format": "wav",
|
||||||
|
"mp3_bitrate": "320k",
|
||||||
|
"wav_sample_rate": "original"
|
||||||
|
}
|
||||||
@@ -1,10 +1,32 @@
|
|||||||
|
# Web 框架
|
||||||
Flask>=2.0.0
|
Flask>=2.0.0
|
||||||
jieba>=0.42.1
|
|
||||||
yt-dlp>=2023.0.0
|
|
||||||
chardet>=5.0.0
|
|
||||||
Werkzeug>=2.0.0
|
Werkzeug>=2.0.0
|
||||||
faster-whisper>=1.0.0
|
requests>=2.28.0
|
||||||
opencc-python-reimplemented>=0.1.7
|
|
||||||
# AI 配音 (GPT-SoVITS 依赖)
|
# 音频处理
|
||||||
soundfile>=0.12.0
|
soundfile>=0.12.0
|
||||||
numpy>=1.20.0
|
numpy>=1.20.0
|
||||||
|
librosa>=0.9.0
|
||||||
|
|
||||||
|
# NLP / 文本处理
|
||||||
|
jieba>=0.42.1
|
||||||
|
chardet>=5.0.0
|
||||||
|
opencc-python-reimplemented>=0.1.7
|
||||||
|
langdetect>=1.0.9
|
||||||
|
|
||||||
|
# 语音 / AI / 机器学习
|
||||||
|
faster-whisper>=1.0.0
|
||||||
|
ctranslate2>=3.20.0
|
||||||
|
transformers>=4.30.0
|
||||||
|
demucs>=4.0.0
|
||||||
|
|
||||||
|
# 配置 / 工具
|
||||||
|
yt-dlp>=2023.0.0
|
||||||
|
python-dotenv>=1.0.0
|
||||||
|
PyYAML>=6.0
|
||||||
|
ml_collections>=0.1.1
|
||||||
|
|
||||||
|
# PyTorch — 请根据 CUDA 版本自行安装
|
||||||
|
# CPU: pip install torch torchvision torchaudio
|
||||||
|
# CUDA: pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu118
|
||||||
|
torch>=2.0.0
|
||||||
|
|||||||
Binary file not shown.
@@ -1,664 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="zh-CN">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='font-awesome.css') }}">
|
|
||||||
<title>AI 翻译</title>
|
|
||||||
<style>
|
|
||||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
||||||
body {
|
|
||||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
|
||||||
background: #f5f5f5; color: #333; height: 100vh; overflow: hidden; display: flex;
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ===== 左侧面板 ===== */
|
|
||||||
.left-panel {
|
|
||||||
width: 460px; flex-shrink: 0; display: flex; flex-direction: column;
|
|
||||||
border-right: 1px solid #e8e8e8; background: #fff; height: 100vh; overflow-y: auto;
|
|
||||||
}
|
|
||||||
.left-panel::-webkit-scrollbar { width: 4px; }
|
|
||||||
.left-panel::-webkit-scrollbar-thumb { background: #ddd; border-radius: 2px; }
|
|
||||||
.left-body { padding: 20px 22px 28px; }
|
|
||||||
|
|
||||||
/* 标题 */
|
|
||||||
.page-header {
|
|
||||||
display: flex; align-items: center; justify-content: space-between; margin-bottom: 4px;
|
|
||||||
}
|
|
||||||
.page-header h1 { font-size: 18px; font-weight: 700; color: #1a1a1a; }
|
|
||||||
.page-header h1 i { color: #0078d4; margin-right: 8px; font-size: 16px; }
|
|
||||||
.page-subtitle { color: #aaa; font-size: 12px; margin-bottom: 18px; }
|
|
||||||
|
|
||||||
/* 设置按钮 */
|
|
||||||
.icon-btn {
|
|
||||||
width: 30px; height: 30px; border: none; background: none;
|
|
||||||
border-radius: 8px; cursor: pointer; font-size: 14px; color: #bbb;
|
|
||||||
display: flex; align-items: center; justify-content: center; transition: all 0.15s;
|
|
||||||
}
|
|
||||||
.icon-btn:hover { background: #f0f0f0; color: #666; }
|
|
||||||
|
|
||||||
/* 设置弹窗 */
|
|
||||||
.modal-overlay {
|
|
||||||
display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
|
|
||||||
background: rgba(0,0,0,0.35); z-index: 1000;
|
|
||||||
justify-content: center; align-items: flex-start; padding-top: 80px;
|
|
||||||
}
|
|
||||||
.modal-overlay.show { display: flex; }
|
|
||||||
.modal {
|
|
||||||
background: #fff; border-radius: 12px; width: 520px;
|
|
||||||
box-shadow: 0 12px 40px rgba(0,0,0,0.2); overflow: hidden;
|
|
||||||
}
|
|
||||||
.modal-head {
|
|
||||||
padding: 14px 18px; border-bottom: 1px solid #eee;
|
|
||||||
display: flex; align-items: center; justify-content: space-between;
|
|
||||||
}
|
|
||||||
.modal-head h3 { font-size: 14px; font-weight: 600; color: #333; }
|
|
||||||
.modal-head h3 i { margin-right: 6px; color: #999; }
|
|
||||||
.modal-close {
|
|
||||||
width: 26px; height: 26px; border: none; background: #f5f5f5;
|
|
||||||
border-radius: 6px; cursor: pointer; font-size: 13px; color: #999;
|
|
||||||
display: flex; align-items: center; justify-content: center;
|
|
||||||
}
|
|
||||||
.modal-close:hover { background: #eee; color: #333; }
|
|
||||||
.modal-body { padding: 16px 18px; }
|
|
||||||
.modal-foot {
|
|
||||||
padding: 10px 18px; border-top: 1px solid #eee;
|
|
||||||
display: flex; justify-content: flex-end; gap: 8px;
|
|
||||||
}
|
|
||||||
.modal-foot button {
|
|
||||||
padding: 6px 18px; font-size: 12px; font-weight: 600;
|
|
||||||
border-radius: 6px; cursor: pointer; transition: all 0.15s;
|
|
||||||
}
|
|
||||||
.btn-cancel { border: 1px solid #e0e0e0; background: #fff; color: #666; }
|
|
||||||
.btn-cancel:hover { background: #f5f5f5; }
|
|
||||||
.btn-save { border: none; background: #0078d4; color: #fff; }
|
|
||||||
.btn-save:hover { background: #006cbd; }
|
|
||||||
|
|
||||||
/* 卡片 */
|
|
||||||
.card {
|
|
||||||
background: #fafafa; border: 1px solid #f0f0f0; border-radius: 10px;
|
|
||||||
padding: 14px 16px; margin-bottom: 10px;
|
|
||||||
}
|
|
||||||
.card-title {
|
|
||||||
font-size: 11px; font-weight: 600; color: #999; text-transform: uppercase;
|
|
||||||
letter-spacing: 0.06em; margin-bottom: 10px; display: flex; align-items: center; gap: 6px;
|
|
||||||
}
|
|
||||||
.card-title i { font-size: 11px; }
|
|
||||||
|
|
||||||
/* 模型列表 */
|
|
||||||
.model-item {
|
|
||||||
display: flex; align-items: center; gap: 8px;
|
|
||||||
padding: 8px 12px; border: 1px solid #e8e8e8; border-radius: 6px;
|
|
||||||
margin-bottom: 5px; cursor: pointer; transition: all 0.15s;
|
|
||||||
font-size: 12px; color: #333; background: #fff;
|
|
||||||
}
|
|
||||||
.model-item:hover { border-color: #0078d4; background: #f0f7ff; }
|
|
||||||
.model-item.active { border-color: #0078d4; background: #e3f2fd; }
|
|
||||||
.model-item .model-name { flex: 1; font-weight: 500; }
|
|
||||||
.model-item .model-status {
|
|
||||||
width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0;
|
|
||||||
}
|
|
||||||
.model-item .model-status.loaded { background: #27ae60; }
|
|
||||||
|
|
||||||
|
|
||||||
/* 表单 */
|
|
||||||
.field { margin-bottom: 8px; }
|
|
||||||
.field:last-child { margin-bottom: 0; }
|
|
||||||
.field label { display: block; font-size: 12px; font-weight: 500; margin-bottom: 3px; color: #555; }
|
|
||||||
.field select, .field input[type="text"] {
|
|
||||||
width: 100%; padding: 7px 10px;
|
|
||||||
border: 1px solid #e0e0e0; border-radius: 6px;
|
|
||||||
background: #fff; color: #333; font-size: 13px;
|
|
||||||
outline: none; transition: all 0.15s;
|
|
||||||
}
|
|
||||||
.field select:focus, .field input[type="text"]:focus {
|
|
||||||
border-color: #0078d4; box-shadow: 0 0 0 2px rgba(0,120,212,0.06);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* 语言行 */
|
|
||||||
.lang-row { display: flex; gap: 6px; align-items: flex-end; }
|
|
||||||
.lang-row .lang-col { flex: 1; }
|
|
||||||
.lang-row .lang-col label { display: block; font-size: 12px; font-weight: 500; margin-bottom: 4px; color: #555; }
|
|
||||||
.lang-row .lang-col select {
|
|
||||||
width: 100%; padding: 8px 10px;
|
|
||||||
border: 1px solid #e0e0e0; border-radius: 6px;
|
|
||||||
background: #fff; color: #333; font-size: 13px;
|
|
||||||
outline: none; transition: all 0.15s;
|
|
||||||
}
|
|
||||||
.lang-row .lang-col select:focus {
|
|
||||||
border-color: #0078d4; box-shadow: 0 0 0 2px rgba(0,120,212,0.06);
|
|
||||||
}
|
|
||||||
.lang-swap-btn {
|
|
||||||
width: 32px; height: 34px; border: 1px solid #e0e0e0; border-radius: 6px;
|
|
||||||
background: #fff; color: #aaa; cursor: pointer; display: flex; align-items: center;
|
|
||||||
justify-content: center; font-size: 12px; flex-shrink: 0; transition: all 0.15s;
|
|
||||||
}
|
|
||||||
.lang-swap-btn:hover { background: #f0f0f0; color: #333; border-color: #ccc; }
|
|
||||||
|
|
||||||
/* textarea */
|
|
||||||
textarea {
|
|
||||||
width: 100%; min-height: 320px; padding: 10px; resize: vertical;
|
|
||||||
border: 1px solid #e0e0e0; border-radius: 6px; background: #fff;
|
|
||||||
color: #333; font-size: 13px; line-height: 1.6; outline: none;
|
|
||||||
transition: all 0.15s; font-family: inherit;
|
|
||||||
}
|
|
||||||
textarea:focus { border-color: #0078d4; box-shadow: 0 0 0 2px rgba(0,120,212,0.06); }
|
|
||||||
|
|
||||||
/* 上传区 */
|
|
||||||
.upload-area {
|
|
||||||
border: 2px dashed #e0e0e0; border-radius: 10px;
|
|
||||||
padding: 24px 16px; text-align: center; cursor: pointer;
|
|
||||||
transition: all 0.2s; background: #fff;
|
|
||||||
}
|
|
||||||
.upload-area:hover, .upload-area.dragover { border-color: #0078d4; background: #f0f7ff; }
|
|
||||||
.upload-area i { font-size: 24px; color: #ccc; margin-bottom: 6px; display: block; }
|
|
||||||
.upload-area .label { font-size: 13px; color: #999; }
|
|
||||||
.upload-area .filename { font-size: 13px; color: #0078d4; font-weight: 600; margin-top: 4px; }
|
|
||||||
.upload-area input[type="file"] { display: none; }
|
|
||||||
|
|
||||||
/* 模式切换 */
|
|
||||||
.mode-tabs {
|
|
||||||
display: flex; gap: 4px; background: #f0f0f0; border-radius: 8px;
|
|
||||||
padding: 3px; margin-bottom: 12px;
|
|
||||||
}
|
|
||||||
.mode-tab {
|
|
||||||
flex: 1; padding: 7px 0; text-align: center; font-size: 13px; font-weight: 500;
|
|
||||||
border-radius: 6px; cursor: pointer; color: #666; transition: all 0.15s;
|
|
||||||
border: none; background: transparent;
|
|
||||||
}
|
|
||||||
.mode-tab.active { background: #fff; color: #0078d4; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
|
|
||||||
|
|
||||||
/* 按钮 */
|
|
||||||
.btn {
|
|
||||||
padding: 7px 14px; border-radius: 7px; font-size: 12px; font-weight: 600;
|
|
||||||
cursor: pointer; transition: all 0.15s; border: none;
|
|
||||||
display: inline-flex; align-items: center; justify-content: center; gap: 5px;
|
|
||||||
}
|
|
||||||
.btn-outline { background: #fff; color: #666; border: 1px solid #e0e0e0; }
|
|
||||||
.btn-outline:hover { background: #f5f5f5; }
|
|
||||||
|
|
||||||
/* 主操作按钮 */
|
|
||||||
.action-btn {
|
|
||||||
width: 100%; padding: 10px 18px;
|
|
||||||
background: linear-gradient(135deg, #0078d4, #005fa3);
|
|
||||||
color: #fff; border: none; border-radius: 8px;
|
|
||||||
font-size: 14px; font-weight: 600; cursor: pointer;
|
|
||||||
display: flex; align-items: center; justify-content: center; gap: 8px;
|
|
||||||
transition: all 0.2s; margin-top: 4px;
|
|
||||||
box-shadow: 0 2px 8px rgba(0,120,212,0.2);
|
|
||||||
}
|
|
||||||
.action-btn:hover:not(:disabled) {
|
|
||||||
background: linear-gradient(135deg, #006cbd, #004e8a);
|
|
||||||
box-shadow: 0 4px 12px rgba(0,120,212,0.3); transform: translateY(-1px);
|
|
||||||
}
|
|
||||||
.action-btn:active:not(:disabled) { transform: translateY(0); }
|
|
||||||
.action-btn:disabled { opacity: 0.4; cursor: not-allowed; transform: none; }
|
|
||||||
|
|
||||||
/* ===== 右侧面板 ===== */
|
|
||||||
.right-panel {
|
|
||||||
flex: 1; display: flex; flex-direction: column; height: 100vh; min-width: 0;
|
|
||||||
}
|
|
||||||
.right-header {
|
|
||||||
padding: 14px 20px; border-bottom: 1px solid #e8e8e8; background: #fff;
|
|
||||||
display: flex; align-items: center; gap: 8px; flex-shrink: 0;
|
|
||||||
}
|
|
||||||
.right-header h2 { font-size: 14px; font-weight: 600; color: #333; }
|
|
||||||
.right-header h2 i { color: #0078d4; margin-right: 6px; }
|
|
||||||
.right-body { flex: 1; display: flex; flex-direction: column; overflow: hidden; }
|
|
||||||
|
|
||||||
/* 进度 spinner */
|
|
||||||
.progress-wrap { padding: 16px 20px; flex-shrink: 0; display: none; align-items: center; gap: 12px; }
|
|
||||||
.progress-wrap.show { display: flex; }
|
|
||||||
.spinner {
|
|
||||||
width: 24px; height: 24px; flex-shrink: 0;
|
|
||||||
border: 3px solid #e0e0e0; border-top-color: #0078d4;
|
|
||||||
border-radius: 50%; animation: spin 0.8s linear infinite;
|
|
||||||
}
|
|
||||||
@keyframes spin { to { transform: rotate(360deg); } }
|
|
||||||
.progress-info { font-size: 13px; color: #555; }
|
|
||||||
.progress-info .pct { font-weight: 600; color: #0078d4; margin-left: 4px; }
|
|
||||||
|
|
||||||
/* 结果 */
|
|
||||||
.result-area { flex: 1; overflow-y: auto; padding: 16px 20px; background: #fff; }
|
|
||||||
.result-area::-webkit-scrollbar { width: 6px; }
|
|
||||||
.result-area::-webkit-scrollbar-thumb { background: #ddd; border-radius: 3px; }
|
|
||||||
.result-placeholder { text-align: center; padding: 60px 20px; color: #ccc; }
|
|
||||||
.result-placeholder i { font-size: 48px; margin-bottom: 12px; display: block; }
|
|
||||||
.result-placeholder .text { font-size: 14px; }
|
|
||||||
.result-text { font-size: 14px; line-height: 1.8; color: #333; white-space: pre-wrap; word-break: break-all; }
|
|
||||||
|
|
||||||
|
|
||||||
/* Toast */
|
|
||||||
.toast-container { position: fixed; top: 20px; right: 20px; z-index: 200; display: flex; flex-direction: column; gap: 8px; }
|
|
||||||
.toast {
|
|
||||||
padding: 10px 16px; border-radius: 8px; font-size: 13px; font-weight: 500;
|
|
||||||
box-shadow: 0 4px 12px rgba(0,0,0,0.15); animation: toastIn 0.3s ease;
|
|
||||||
max-width: 360px;
|
|
||||||
}
|
|
||||||
.toast.success { background: #e8f5e9; color: #2e7d32; border: 1px solid #c8e6c9; }
|
|
||||||
.toast.error { background: #fce4ec; color: #c62828; border: 1px solid #f8bbd0; }
|
|
||||||
.toast.info { background: #e3f2fd; color: #1565c0; border: 1px solid #bbdefb; }
|
|
||||||
@keyframes toastIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
|
|
||||||
|
|
||||||
/* 全屏加载遮罩 */
|
|
||||||
.loading-overlay {
|
|
||||||
display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
|
|
||||||
background: rgba(0,0,0,0.45); z-index: 3000;
|
|
||||||
justify-content: center; align-items: center; flex-direction: column; gap: 16px;
|
|
||||||
}
|
|
||||||
.loading-overlay.show { display: flex; }
|
|
||||||
.loading-overlay .loading-spinner {
|
|
||||||
width: 40px; height: 40px;
|
|
||||||
border: 4px solid rgba(255,255,255,0.3); border-top-color: #fff;
|
|
||||||
border-radius: 50%; animation: spin 0.8s linear infinite;
|
|
||||||
}
|
|
||||||
.loading-overlay .loading-text { color: #fff; font-size: 15px; font-weight: 500; }
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="toast-container" id="toastContainer"></div>
|
|
||||||
<div class="loading-overlay" id="loadingOverlay">
|
|
||||||
<div class="loading-spinner"></div>
|
|
||||||
<div class="loading-text" id="loadingText">正在加载模型,请稍候...</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ===== 左侧面板 ===== -->
|
|
||||||
<div class="left-panel">
|
|
||||||
<div class="left-body">
|
|
||||||
|
|
||||||
<!-- 标题 -->
|
|
||||||
<div class="page-header">
|
|
||||||
<h1><i class="fas fa-language"></i>AI 翻译</h1>
|
|
||||||
<button class="icon-btn" onclick="openSettings()" title="设置"><i class="fas fa-gear"></i></button>
|
|
||||||
</div>
|
|
||||||
<div class="page-subtitle">NLLB-200 本地翻译 · 点击齿轮配置模型目录</div>
|
|
||||||
|
|
||||||
<!-- 设置弹窗 -->
|
|
||||||
<div class="modal-overlay" id="settingsOverlay" onclick="closeSettings(event)">
|
|
||||||
<div class="modal" onclick="event.stopPropagation()">
|
|
||||||
<div class="modal-head">
|
|
||||||
<h3><i class="fas fa-gear"></i>NLLB-200 模型配置</h3>
|
|
||||||
<button class="modal-close" onclick="closeSettings()"><i class="fas fa-times"></i></button>
|
|
||||||
</div>
|
|
||||||
<div class="modal-body">
|
|
||||||
<div class="field">
|
|
||||||
<label>模型目录(HF 目录或模型 ID)</label>
|
|
||||||
<input type="text" id="dir_nllb" value="{{ config.nllb_dir }}" placeholder="E:\AI\ai-translation\nllb">
|
|
||||||
</div>
|
|
||||||
<div style="margin-top:10px;padding:8px 10px;background:#f0f7ff;border:1px solid #d0e3f7;border-radius:6px;font-size:12px;display:flex;align-items:center;gap:6px;">
|
|
||||||
<span style="color:#999;">当前模型:</span>
|
|
||||||
<span id="currentModelName" style="color:#0078d4;font-weight:600;">未加载</span>
|
|
||||||
</div>
|
|
||||||
<div style="margin-top:12px;">
|
|
||||||
<label style="display:block;font-size:12px;font-weight:500;margin-bottom:6px;color:#555;">选择模型</label>
|
|
||||||
<div id="modelListContent">
|
|
||||||
<div style="color:#999;font-size:12px;">加载中...</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="modal-foot">
|
|
||||||
<button class="btn-cancel" onclick="unloadModel()" style="margin-right:auto;border:1px solid #e74c3c;color:#e74c3c;">卸载模型</button>
|
|
||||||
<button class="btn-cancel" onclick="closeSettings()">取消</button>
|
|
||||||
<button class="btn-save" onclick="saveSettings()">保存</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 模式切换 -->
|
|
||||||
<div class="mode-tabs">
|
|
||||||
<button class="mode-tab active" id="tabText" onclick="switchMode('text')">文本翻译</button>
|
|
||||||
<button class="mode-tab" id="tabFile" onclick="switchMode('file')">字幕翻译</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 语言设置 -->
|
|
||||||
<div class="card">
|
|
||||||
<div class="card-title" style="justify-content:space-between;">
|
|
||||||
<span><i class="fas fa-globe"></i> 语言设置</span>
|
|
||||||
<button onclick="saveLangs()" style="border:none;background:#0078d4;color:#fff;font-size:11px;padding:3px 10px;border-radius:4px;cursor:pointer;text-transform:none;letter-spacing:0;">保存</button>
|
|
||||||
</div>
|
|
||||||
<div class="lang-row">
|
|
||||||
<div class="lang-col">
|
|
||||||
<label>源语言</label>
|
|
||||||
<select id="srcLang">
|
|
||||||
<option value="auto" {% if config.last_src_lang == 'auto' %}selected{% endif %}>自动检测</option>
|
|
||||||
{% for code, name in languages.items() %}{% if code != 'auto' %}
|
|
||||||
<option value="{{ code }}" {% if code == config.last_src_lang %}selected{% endif %}>{{ name }}</option>
|
|
||||||
{% endif %}{% endfor %}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<button class="lang-swap-btn" onclick="swapLangs()" title="交换语言">
|
|
||||||
<i class="fas fa-exchange-alt"></i>
|
|
||||||
</button>
|
|
||||||
<div class="lang-col">
|
|
||||||
<label>目标语言</label>
|
|
||||||
<select id="tgtLang">
|
|
||||||
{% for code, name in languages.items() %}{% if code != 'auto' %}
|
|
||||||
<option value="{{ code }}" {% if code == config.last_tgt_lang %}selected{% endif %}>{{ name }}</option>
|
|
||||||
{% endif %}{% endfor %}
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 文本翻译 -->
|
|
||||||
<div id="textSection">
|
|
||||||
<div class="card">
|
|
||||||
<div class="card-title"><i class="fas fa-pen"></i> 输入文本</div>
|
|
||||||
<div class="field">
|
|
||||||
<textarea id="inputText" placeholder="请输入要翻译的文本,每行一句或多段落..."></textarea>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button class="action-btn" id="btnTranslateText" onclick="translateText()">
|
|
||||||
<i class="fas fa-language"></i> 开始翻译
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 字幕翻译 -->
|
|
||||||
<div id="fileSection" style="display:none;">
|
|
||||||
<div class="card">
|
|
||||||
<div class="card-title"><i class="fas fa-file"></i> 上传字幕</div>
|
|
||||||
<div class="upload-area" id="uploadArea" onclick="document.getElementById('subtitleFile').click()">
|
|
||||||
<i class="fas fa-file"></i>
|
|
||||||
<div class="label" id="uploadLabel">点击或拖拽上传字幕文件(SRT / ASS / VTT)</div>
|
|
||||||
<div class="filename" id="uploadFilename" style="display:none;"></div>
|
|
||||||
<input type="file" id="subtitleFile" accept=".srt,.ass,.ssa,.vtt">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<button class="action-btn" id="btnTranslateFile" onclick="translateFile()">
|
|
||||||
<i class="fas fa-language"></i> 翻译字幕
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- ===== 右侧面板 ===== -->
|
|
||||||
<div class="right-panel">
|
|
||||||
<div class="right-header">
|
|
||||||
<h2><i class="fas fa-language"></i>翻译结果</h2>
|
|
||||||
<button class="btn btn-outline" id="btnDownload" style="display:none;margin-left:auto;padding:5px 14px;font-size:12px;" onclick="downloadResult()">
|
|
||||||
<i class="fas fa-download"></i> 下载字幕
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<div class="right-body">
|
|
||||||
<div class="progress-wrap" id="progressWrap">
|
|
||||||
<div class="spinner"></div>
|
|
||||||
<div class="progress-info">翻译中<span class="pct" id="progressText">0%</span></div>
|
|
||||||
</div>
|
|
||||||
<div class="result-area" id="resultArea">
|
|
||||||
<div class="result-placeholder">
|
|
||||||
<i class="fas fa-language"></i>
|
|
||||||
<div class="text">翻译结果将显示在这里</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
var currentMode = 'text';
|
|
||||||
var currentTaskId = null;
|
|
||||||
|
|
||||||
// ===== Toast =====
|
|
||||||
function showMessage(text, type, duration) {
|
|
||||||
type = type || 'info'; duration = duration || 3000;
|
|
||||||
var t = document.createElement('div');
|
|
||||||
t.className = 'toast ' + type;
|
|
||||||
t.textContent = text;
|
|
||||||
document.getElementById('toastContainer').appendChild(t);
|
|
||||||
setTimeout(function() { t.style.opacity = '0'; t.style.transition = 'opacity 0.3s'; setTimeout(function() { t.remove(); }, 300); }, duration);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 设置弹窗 =====
|
|
||||||
function openSettings() {
|
|
||||||
document.getElementById('settingsOverlay').classList.add('show');
|
|
||||||
scanModels();
|
|
||||||
refreshModelStatus();
|
|
||||||
}
|
|
||||||
function closeSettings(e) {
|
|
||||||
if (e && e.target !== document.getElementById('settingsOverlay')) return;
|
|
||||||
document.getElementById('settingsOverlay').classList.remove('show');
|
|
||||||
}
|
|
||||||
|
|
||||||
function refreshModelStatus() {
|
|
||||||
fetch('/ai-translate/model-status').then(function(r) { return r.json(); }).then(function(data) {
|
|
||||||
var el = document.getElementById('currentModelName');
|
|
||||||
if (data.loaded && data.model_name) {
|
|
||||||
el.textContent = data.model_name;
|
|
||||||
el.style.color = '#27ae60';
|
|
||||||
} else {
|
|
||||||
el.textContent = '未加载';
|
|
||||||
el.style.color = '#999';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function unloadModel() {
|
|
||||||
var overlay = document.getElementById('loadingOverlay');
|
|
||||||
document.getElementById('loadingText').textContent = '正在卸载模型...';
|
|
||||||
overlay.classList.add('show');
|
|
||||||
fetch('/ai-translate/unload-model', {method: 'POST'})
|
|
||||||
.then(function(r) { return r.json(); }).then(function(data) {
|
|
||||||
overlay.classList.remove('show');
|
|
||||||
document.getElementById('loadingText').textContent = '正在加载模型,请稍候...';
|
|
||||||
showMessage('模型已卸载', 'success');
|
|
||||||
refreshModelStatus();
|
|
||||||
scanModels();
|
|
||||||
}).catch(function() {
|
|
||||||
overlay.classList.remove('show');
|
|
||||||
document.getElementById('loadingText').textContent = '正在加载模型,请稍候...';
|
|
||||||
showMessage('卸载失败', 'error');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveSettings() {
|
|
||||||
fetch('/ai-translate/config', {
|
|
||||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
||||||
body: JSON.stringify({ nllb_dir: document.getElementById('dir_nllb').value.trim() })
|
|
||||||
}).then(function(r) { return r.json(); }).then(function() {
|
|
||||||
showMessage('目录配置已保存', 'success');
|
|
||||||
scanModels();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 模式切换 =====
|
|
||||||
function switchMode(mode) {
|
|
||||||
currentMode = mode;
|
|
||||||
document.getElementById('tabText').className = 'mode-tab' + (mode === 'text' ? ' active' : '');
|
|
||||||
document.getElementById('tabFile').className = 'mode-tab' + (mode === 'file' ? ' active' : '');
|
|
||||||
document.getElementById('textSection').style.display = mode === 'text' ? '' : 'none';
|
|
||||||
document.getElementById('fileSection').style.display = mode === 'file' ? '' : 'none';
|
|
||||||
document.getElementById('btnDownload').style.display = 'none';
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 语言 =====
|
|
||||||
function swapLangs() {
|
|
||||||
var src = document.getElementById('srcLang'), tgt = document.getElementById('tgtLang');
|
|
||||||
if (src.value === 'auto') { showMessage('源语言为"自动检测"时无法交换', 'error'); return; }
|
|
||||||
var tmp = src.value; src.value = tgt.value; tgt.value = tmp;
|
|
||||||
}
|
|
||||||
|
|
||||||
function saveLangs() {
|
|
||||||
fetch('/ai-translate/config', {
|
|
||||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
||||||
body: JSON.stringify({
|
|
||||||
last_src_lang: document.getElementById('srcLang').value,
|
|
||||||
last_tgt_lang: document.getElementById('tgtLang').value
|
|
||||||
})
|
|
||||||
}).then(function(r) { return r.json(); }).then(function() {
|
|
||||||
showMessage('语言设置已保存', 'success');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 扫描模型 =====
|
|
||||||
function scanModels() {
|
|
||||||
var content = document.getElementById('modelListContent');
|
|
||||||
content.innerHTML = '<div style="color:#999;font-size:12px;">加载中...</div>';
|
|
||||||
fetch('/ai-translate/models')
|
|
||||||
.then(function(r) { return r.json(); })
|
|
||||||
.then(function(data) {
|
|
||||||
var models = data.models || [];
|
|
||||||
if (!models.length) {
|
|
||||||
content.innerHTML = '<div style="color:#e74c3c;font-size:12px;">未找到模型,请在设置中配置目录</div>';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
var lastModel = data.last_model || '';
|
|
||||||
var html = '';
|
|
||||||
models.forEach(function(m) {
|
|
||||||
var isActive = m.name === lastModel;
|
|
||||||
html += '<div class="model-item' + (isActive ? ' active' : '') + '" onclick="loadModel(\'' + m.name.replace(/'/g, "\\'") + '\')">';
|
|
||||||
html += '<span class="model-name">' + m.name + '</span>';
|
|
||||||
if (isActive) html += '<span class="model-status loaded"></span>';
|
|
||||||
html += '</div>';
|
|
||||||
});
|
|
||||||
content.innerHTML = html;
|
|
||||||
}).catch(function() {
|
|
||||||
content.innerHTML = '<div style="color:#e74c3c;font-size:12px;">加载失败,请刷新重试</div>';
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 加载模型 =====
|
|
||||||
function loadModel(name) {
|
|
||||||
var overlay = document.getElementById('loadingOverlay');
|
|
||||||
overlay.classList.add('show');
|
|
||||||
|
|
||||||
fetch('/ai-translate/load-model', {
|
|
||||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
||||||
body: JSON.stringify({model_name: name, engine_type: 'nllb'})
|
|
||||||
})
|
|
||||||
.then(function(r) { return r.json(); })
|
|
||||||
.then(function(data) {
|
|
||||||
overlay.classList.remove('show');
|
|
||||||
if (data.success) {
|
|
||||||
showMessage('模型加载成功: ' + name, 'success');
|
|
||||||
} else {
|
|
||||||
showMessage(data.error || '加载失败', 'error');
|
|
||||||
}
|
|
||||||
scanModels();
|
|
||||||
refreshModelStatus();
|
|
||||||
}).catch(function() {
|
|
||||||
overlay.classList.remove('show');
|
|
||||||
showMessage('加载失败', 'error');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 翻译 =====
|
|
||||||
function translateText() {
|
|
||||||
var text = document.getElementById('inputText').value.trim();
|
|
||||||
if (!text) { showMessage('请输入要翻译的文本', 'error'); return; }
|
|
||||||
document.getElementById('btnTranslateText').disabled = true;
|
|
||||||
showProgress(0);
|
|
||||||
|
|
||||||
fetch('/ai-translate/translate-text', {
|
|
||||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
|
||||||
body: JSON.stringify({
|
|
||||||
text: text,
|
|
||||||
src_lang: document.getElementById('srcLang').value,
|
|
||||||
tgt_lang: document.getElementById('tgtLang').value
|
|
||||||
})
|
|
||||||
}).then(function(r) { return r.json(); }).then(function(data) {
|
|
||||||
if (data.success) { currentTaskId = data.task_id; pollTask(); }
|
|
||||||
else { showMessage(data.error || '翻译失败', 'error'); resetBtns(); hideProgress(); }
|
|
||||||
}).catch(function() { resetBtns(); hideProgress(); });
|
|
||||||
}
|
|
||||||
|
|
||||||
function translateFile() {
|
|
||||||
var fi = document.getElementById('subtitleFile');
|
|
||||||
if (!fi.files.length) { showMessage('请上传字幕文件', 'error'); return; }
|
|
||||||
|
|
||||||
document.getElementById('btnTranslateFile').disabled = true;
|
|
||||||
showProgress(0);
|
|
||||||
|
|
||||||
var fd = new FormData();
|
|
||||||
fd.append('subtitle', fi.files[0]);
|
|
||||||
fd.append('src_lang', document.getElementById('srcLang').value);
|
|
||||||
fd.append('tgt_lang', document.getElementById('tgtLang').value);
|
|
||||||
|
|
||||||
fetch('/ai-translate/translate-file', {method: 'POST', body: fd})
|
|
||||||
.then(function(r) { return r.json(); }).then(function(data) {
|
|
||||||
if (data.success) { currentTaskId = data.task_id; pollTask(); }
|
|
||||||
else { showMessage(data.error || '翻译失败', 'error'); resetBtns(); hideProgress(); }
|
|
||||||
}).catch(function() { resetBtns(); hideProgress(); });
|
|
||||||
}
|
|
||||||
|
|
||||||
function pollTask() {
|
|
||||||
if (!currentTaskId) return;
|
|
||||||
fetch('/ai-translate/task-status/' + currentTaskId)
|
|
||||||
.then(function(r) { return r.json(); }).then(function(data) {
|
|
||||||
if (!data.success) return;
|
|
||||||
if (data.progress !== undefined) showProgress(data.progress);
|
|
||||||
if (data.status === 'done') {
|
|
||||||
showResult(data.result || '');
|
|
||||||
if (data.file_path) document.getElementById('btnDownload').style.display = '';
|
|
||||||
showMessage('翻译完成', 'success');
|
|
||||||
resetBtns(); hideProgress(); currentTaskId = null;
|
|
||||||
} else if (data.status === 'error') {
|
|
||||||
showMessage('翻译失败: ' + (data.error || '未知错误'), 'error');
|
|
||||||
resetBtns(); hideProgress(); currentTaskId = null;
|
|
||||||
} else { setTimeout(pollTask, 500); }
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function showResult(text) {
|
|
||||||
var el = document.getElementById('resultArea');
|
|
||||||
el.innerHTML = '<div class="result-text"></div>';
|
|
||||||
el.querySelector('.result-text').textContent = text;
|
|
||||||
}
|
|
||||||
function resetBtns() {
|
|
||||||
document.getElementById('btnTranslateText').disabled = false;
|
|
||||||
document.getElementById('btnTranslateFile').disabled = false;
|
|
||||||
}
|
|
||||||
function showProgress(p) {
|
|
||||||
document.getElementById('progressWrap').classList.add('show');
|
|
||||||
document.getElementById('progressText').textContent = p + '%';
|
|
||||||
}
|
|
||||||
function hideProgress() { document.getElementById('progressWrap').classList.remove('show'); }
|
|
||||||
|
|
||||||
// ===== 下载 =====
|
|
||||||
function downloadResult() {
|
|
||||||
if (currentTaskId) window.open('/ai-translate/download/' + currentTaskId, '_blank');
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 文件上传 =====
|
|
||||||
var ua = document.getElementById('uploadArea');
|
|
||||||
var sf = document.getElementById('subtitleFile');
|
|
||||||
ua.addEventListener('dragover', function(e) { e.preventDefault(); ua.classList.add('dragover'); });
|
|
||||||
ua.addEventListener('dragleave', function() { ua.classList.remove('dragover'); });
|
|
||||||
ua.addEventListener('drop', function(e) {
|
|
||||||
e.preventDefault(); ua.classList.remove('dragover');
|
|
||||||
if (e.dataTransfer.files.length) { sf.files = e.dataTransfer.files; onFileSel(); }
|
|
||||||
});
|
|
||||||
sf.addEventListener('change', onFileSel);
|
|
||||||
function onFileSel() {
|
|
||||||
var f = sf.files[0];
|
|
||||||
if (f) {
|
|
||||||
document.getElementById('uploadLabel').style.display = 'none';
|
|
||||||
var fn = document.getElementById('uploadFilename');
|
|
||||||
fn.style.display = ''; fn.textContent = f.name;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== 初始化 =====
|
|
||||||
(function() {
|
|
||||||
// 页面加载时检查模型是否正在加载中
|
|
||||||
fetch('/ai-translate/model-status').then(function(r) { return r.json(); }).then(function(data) {
|
|
||||||
if (data.loading) {
|
|
||||||
var overlay = document.getElementById('loadingOverlay');
|
|
||||||
overlay.classList.add('show');
|
|
||||||
// 轮询直到加载完成
|
|
||||||
var timer = setInterval(function() {
|
|
||||||
fetch('/ai-translate/model-status').then(function(r) { return r.json(); }).then(function(d) {
|
|
||||||
if (!d.loading) {
|
|
||||||
clearInterval(timer);
|
|
||||||
overlay.classList.remove('show');
|
|
||||||
if (d.loaded) {
|
|
||||||
showMessage('模型加载成功: ' + (d.model_name || ''), 'success');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}, 1000);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
})();
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1262,7 +1262,6 @@
|
|||||||
{ id: 'data-manage', name: '数据管理', icon: 'fa-database', url: '/data-manage', section: '概览' },
|
{ id: 'data-manage', name: '数据管理', icon: 'fa-database', url: '/data-manage', section: '概览' },
|
||||||
{ id: 'pin-tu', name: '路径文件查阅器', icon: 'fa-images', url: '/pin-tu', section: '工具' },
|
{ id: 'pin-tu', name: '路径文件查阅器', icon: 'fa-images', url: '/pin-tu', section: '工具' },
|
||||||
{ id: 'down-video', name: 'XBIY视频下载器', icon: 'fa-video', url: '/down-video', section: '工具' },
|
{ id: 'down-video', name: 'XBIY视频下载器', icon: 'fa-video', url: '/down-video', section: '工具' },
|
||||||
{ id: 'ai-translate', name: 'NLLB 翻译与字幕', icon: 'fa-language', url: '/ai-translate',section: '工具' },
|
|
||||||
{ id: 'content-tag', name: 'AI生成文章标签', icon: 'fa-tags', url: '/content-tag', section: '工具' },
|
{ id: 'content-tag', name: 'AI生成文章标签', icon: 'fa-tags', url: '/content-tag', section: '工具' },
|
||||||
{ id: 'mp4-to-audio', name: 'VTA 视频转音频', icon: 'fa-video', url: '/mp4-to-audio',section: '工具' },
|
{ id: 'mp4-to-audio', name: 'VTA 视频转音频', icon: 'fa-video', url: '/mp4-to-audio',section: '工具' },
|
||||||
{ id: 'audio-slicer', name: 'AS 智能音频分割', icon: 'fa-scissors', url: '/audio-slicer',section: '工具' },
|
{ id: 'audio-slicer', name: 'AS 智能音频分割', icon: 'fa-scissors', url: '/audio-slicer',section: '工具' },
|
||||||
|
|||||||
Reference in New Issue
Block a user