import time import os import logging from io import StringIO import gradio as gr import pandas as pd from pypinyin import lazy_pinyin from gradio_i18n import gettext, Translate from api import generate_api, get_audio from utils import get_length # 翻译文件位置 trans_file = os.path.join(os.path.dirname(__file__),"i18n", "translations.json") # 关闭aiohttp的DEBUG日志 logging.getLogger('aiohttp').setLevel(logging.WARNING) logging.getLogger("gradio").setLevel(logging.WARNING) # 带有时间的log logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') header = "header" terms = "terms" def load_characters_csv(lang): name = os.path.join(os.path.dirname(__file__), "i18n", f"characters_{lang}.csv") return pd.read_csv(name) def update_all_characters(lang, current_all_characters): new_characters = load_characters_csv(lang) initial_characters = get_characters(kind="原神", all_characters=new_characters) return new_characters, initial_characters, gr.Gallery(value=[[char['头像'], char['名称']] for char in initial_characters], show_label=False, elem_id="character_gallery", columns=[11], object_fit="contain", height="auto", interactive=False, allow_preview=False, selected_index=None) def get_characters(query=None, page=1, per_page=400, kind="原神", lang="zh", all_characters=None): # 使用传入的 all_characters 参数 filtered_characters = all_characters[all_characters["类别"] == kind] if query: # 使用拼音和汉字进行搜索 filtered_characters = filtered_characters[ filtered_characters['名称'].str.contains(query, case=False) ] if filtered_characters.empty and lang == 'zh': filtered_characters = all_characters[all_characters["类别"] == kind] filtered_characters = filtered_characters[ filtered_characters['名称'].apply(lambda x: ''.join(lazy_pinyin(x))).str.contains(query, case=False) ] # 按名称分组,并选择每组的第一个记录 unique_characters = filtered_characters.groupby('名称').first().reset_index().sort_values(by='id') # 应用分页 start_index = (page - 1) * per_page end_index = start_index + per_page return unique_characters.iloc[start_index:end_index].to_dict('records') async def generate(selected_character = None, selected_characters = [], text = "", lang="zh"): # print("-------",selected_character) # print("-------",selected_characters) if selected_character: characters = [selected_character] + selected_characters else: characters = selected_characters if not selected_character and not selected_characters: if lang == "zh": raise gr.Error("请先选择一个角色") elif lang == "en": raise gr.Error("Please select a character first") elif lang == "ja": raise gr.Error("まず、キャラクターを選択してください") elif lang == "ko": raise gr.Error("먼저 캐릭터를 선택하세요") voice_ids = [char.get("voice_id") for char in characters if char.get("voice_id")] if not voice_ids: raise gr.Error("所选角色没有关联的 voice_id") start_time = time.time() # 假设我们只使用第一个选择的角色的名称 if voice_ids == "1": if lang == "zh": raise gr.Error("该角色暂未创建语音") elif lang == "en": raise gr.Error("The character has not been created yet") elif lang == "ja": raise gr.Error("そのキャラクターの音声はまだ作成されていません") elif lang == "ko": raise gr.Error("해당 캐릭터의 음성이 아직 생성되지 않았습니다") if text == "": if lang == "zh": raise gr.Error("请输入需要合成的文本") elif lang == "en": raise gr.Error("Please enter the text to be synthesized") elif lang == "ja": raise gr.Error("合成するテキストを入力してください") elif lang == "ko": raise gr.Error("합성할 텍스트를 입력하세요") if get_length(text) > 1024: if lang == "zh": raise gr.Error("长度请控制在1024个字符以内") elif lang == "en": raise gr.Error("The text length exceeds 1024 words") elif lang == "ja": raise gr.Error("テキストの長さが1024文字を超えています") elif lang == "ko": raise gr.Error("텍스트 길이가 1024자를 초과합니다") audio = await generate_api(voice_ids, text) end_time = time.time() if lang == "zh": cost_time = f"合成共花费{end_time - start_time:.2f}秒" elif lang == "en": cost_time = f"Total time spent synthesizing: {end_time - start_time:.2f} seconds" elif lang == "ja": cost_time = f"合成にかかった時間: {end_time - start_time:.2f}秒" elif lang == "ko": cost_time = f"합성에 소요된 시간: {end_time - start_time:.2f}초" if isinstance(audio, str): print(audio) raise gr.Error(audio) else: return audio, cost_time def get_character_emotions(character, all_characters): # 从all_characters中筛选出与当前角色名称相同的所有记录 character_records = all_characters[all_characters['名称'] == character['名称']] # 按情绪去重并获取完整的角色信息 character_infos = character_records.drop_duplicates(subset=['情绪']).to_dict('records') # 如果没有找到角色信息,返回一个包含默认值的字典 return character_infos if character_infos else [{"名称": character['名称'], "情绪": "默认情绪"}] def update_character_info(character_name, emotion, current_character, all_characters): character_info = None if character_name and emotion: character_info = all_characters[(all_characters['名称'] == character_name) & (all_characters['情绪'] == emotion)] if character_name == "": return None character_info = character_info.iloc[0].to_dict() return character_info, all_characters def add_new_voice(current_character, selected_characters, kind, lang, all_characters): if not current_character: if lang == "zh": raise gr.Error("请先选择一个角色") elif lang == "en": raise gr.Error("Please select a character first") elif lang == "ja": raise gr.Error("まず、キャラクターを選択してください") elif lang == "ko": raise gr.Error("먼저 캐릭터를 선택하세요") if len(selected_characters) >= 5: raise gr.Error("已达到最大选择数(5个)") # 检查是否已存在相同角色 existing_char = next((char for char in selected_characters if char['名称'] == current_character['名称']), None) if existing_char: # 如果情绪不同,更新情绪 if existing_char['情绪'] != current_character['情绪']: existing_char['情绪'] = current_character['情绪'] else: selected_characters.insert(0, current_character) updated_characters = get_characters(kind=kind, lang=lang, all_characters=all_characters) # ! 取消gallery选中状态,返回个新的gallery是必要的,否则会保留上一次的选中状态。这里sonnet很喜欢改成返回一个数组,但这不能清空gallery的选中状态 updated_gallery = gr.Gallery(value=[[char['头像'], char['名称']] for char in updated_characters], show_label=False, elem_id="character_gallery", columns=[11], object_fit="contain", height="auto", interactive=False, allow_preview=False, selected_index=None) return (None, gr.update(value=""), gr.update(choices=[]), selected_characters, updated_characters, updated_gallery, gr.update(visible=True), all_characters) def update_selected_chars_display(selected_characters): updates = [] for i, (name, emotion, _, row) in enumerate(selected_chars_rows): if i < len(selected_characters): char = selected_characters[i] updates.extend([ gr.update(value=char['名称'], visible=True), gr.update(value=char['情绪'], visible=True), gr.update(visible=True), gr.update(visible=True) ]) else: updates.extend([ gr.update(value="", visible=False), gr.update(value="", visible=False), gr.update(visible=False), gr.update(visible=False) ]) return updates def remove_character(index, selected_characters): if 0 <= index < len(selected_characters): del selected_characters[index] return selected_characters, gr.update(visible=True) def update_gallery(kind, query, all_characters): updated_characters = get_characters(kind=kind, query=query, lang=lang, all_characters=all_characters) return updated_characters, [[char['头像'], char['名称']] for char in updated_characters], all_characters def on_select(evt: gr.SelectData, characters, selected_characters, all_characters): # 如果没有选择角色,换人的时候清空 if len(selected_characters) == 0: selected_characters = [] selected = characters[evt.index] emotions = get_character_emotions(selected, all_characters) normal_index = 0 for index, emotion in enumerate(emotions): if emotion["情绪"] == "正常" or emotion["情绪"] == "보통" or emotion["情绪"] == "normal": normal_index = index break default_emotion = emotions[normal_index]["情绪"] if emotions else "" default_voice_id = emotions[normal_index]["voice_id"] if emotions else "" character_dict = selected.copy() character_dict['情绪'] = default_emotion character_dict['voice_id'] = default_voice_id return selected["名称"], gr.Dropdown(choices=[emotion["情绪"] for emotion in emotions], value=default_emotion), character_dict, selected_characters async def update_prompt_audio(current_character): if current_character: return await get_audio(current_character.get("voice_id")) else: return None head = """