| import http.client |
| import json |
| import base64 |
| import os |
| import random |
| import sys |
|
|
| |
| API_HOST = "api2.aigcbest.top" |
| |
| API_KEY = "Bearer sk-adCUrxA2Itnm24VHdNODmeFATufbQEDqz76993UwT6qi4WIc" |
| DEBUG_RESPONSE_FILENAME = "api_last_response.json" |
|
|
| |
| VOICES = ["alloy", "ash", "ballad", "coral", "echo", "fable", "nova", "onyx", "sage", "shimmer"] |
|
|
| |
| OUTPUT_DIR = "/data/liyangzhuo/a" |
|
|
| def ensure_output_directory(): |
| """确保输出目录存在""" |
| if not os.path.exists(OUTPUT_DIR): |
| os.makedirs(OUTPUT_DIR, exist_ok=True) |
| print(f"创建输出目录: {OUTPUT_DIR}") |
|
|
| def select_two_different_voices(): |
| """从音色列表中随机选择两个不同的音色""" |
| selected_voices = random.sample(VOICES, 2) |
| return selected_voices[0], selected_voices[1] |
|
|
| def call_audio_api(text_content, voice, person_type): |
| """调用音频API生成语音""" |
| |
| prompt = f"Please retell the following text in a natural dialogue scene to a high standard of naturalness, using appropriate rhyme and mood based on the following. Please repeat the content accurately and do not add anything:\n\n{text_content}" |
| |
| payload_dict = { |
| "model": "gemini-2.5-flash-all", |
| "modalities": ["text", "audio"], |
| "audio": {"voice": voice, "format": "wav"}, |
| "messages": [{"role": "user", "content": prompt}] |
| } |
| payload = json.dumps(payload_dict) |
|
|
| headers = { |
| 'Accept': 'application/json', |
| 'Authorization': API_KEY, |
| 'Content-Type': 'application/json' |
| } |
|
|
| conn = None |
| try: |
| print(f"正在为{person_type}生成音频 (音色: {voice})...") |
| conn = http.client.HTTPSConnection(API_HOST) |
| |
| conn.request("POST", "/v1/chat/completions", payload, headers) |
| res = conn.getresponse() |
| response_body = res.read() |
| |
| print(f"响应状态码: {res.status} {res.reason}") |
|
|
| response_text = response_body.decode('utf-8') |
| response_json = json.loads(response_text) |
|
|
| |
| debug_filename = f"api_response_{person_type}.json" |
| with open(debug_filename, "w", encoding="utf-8") as f: |
| json.dump(response_json, f, indent=2, ensure_ascii=False) |
|
|
| if res.status == 200 and 'error' not in response_json: |
| try: |
| message = response_json.get('choices', [{}])[0].get('message', {}) |
| audio_info = message.get('audio', {}) |
| |
| audio_base64_data = audio_info.get('data') |
| transcript = audio_info.get('transcript') |
|
|
| if audio_base64_data: |
| audio_binary_data = base64.b64decode(audio_base64_data) |
| return audio_binary_data, transcript |
| else: |
| print(f"警告: 未找到{person_type}的音频数据") |
| return None, None |
|
|
| except (IndexError, AttributeError) as e: |
| print(f"解析{person_type}响应时出错: {e}") |
| return None, None |
| else: |
| print(f"{person_type}请求失败:") |
| if 'error' in response_json: |
| print(json.dumps(response_json['error'], indent=2, ensure_ascii=False)) |
| return None, None |
|
|
| except Exception as e: |
| print(f"{person_type}API调用过程中发生错误: {e}") |
| return None, None |
| finally: |
| if conn: |
| conn.close() |
|
|
| def process_json_file(json_file_path): |
| """处理JSON文件中的所有对话条目""" |
| try: |
| with open(json_file_path, 'r', encoding='utf-8') as f: |
| data = json.load(f) |
| |
| |
| if isinstance(data, dict): |
| data = [data] |
| |
| print(f"开始处理 {len(data)} 个对话条目...") |
| |
| for i, item in enumerate(data): |
| try: |
| item_id = item.get('id', f'item_{i}') |
| person_a_text = item.get('person_a', '') |
| person_b_text = item.get('person_b', '') |
| |
| if not person_a_text or not person_b_text: |
| print(f"跳过条目 {item_id}: 缺少person_a或person_b内容") |
| continue |
| |
| print(f"\n处理条目 {item_id} ({i+1}/{len(data)})...") |
| |
| |
| voice_a, voice_b = select_two_different_voices() |
| print(f"选择音色: person_a={voice_a}, person_b={voice_b}") |
| |
| |
| audio_data_a, transcript_a = call_audio_api(person_a_text, voice_a, "person_a") |
| if audio_data_a: |
| filename_a = f"{item_id}_person_a.wav" |
| filepath_a = os.path.join(OUTPUT_DIR, filename_a) |
| with open(filepath_a, "wb") as f: |
| f.write(audio_data_a) |
| print(f"✅ person_a 音频已保存: {filepath_a}") |
| else: |
| print(f"❌ person_a 音频生成失败") |
| |
| |
| audio_data_b, transcript_b = call_audio_api(person_b_text, voice_b, "person_b") |
| if audio_data_b: |
| filename_b = f"{item_id}_person_b.wav" |
| filepath_b = os.path.join(OUTPUT_DIR, filename_b) |
| with open(filepath_b, "wb") as f: |
| f.write(audio_data_b) |
| print(f"✅ person_b 音频已保存: {filepath_b}") |
| else: |
| print(f"❌ person_b 音频生成失败") |
| |
| except Exception as e: |
| print(f"处理条目 {item.get('id', i)} 时发生错误: {e}") |
| continue |
| |
| print(f"\n✅ 完成处理JSON文件: {json_file_path}") |
| |
| except Exception as e: |
| print(f"读取JSON文件时发生错误: {e}") |
|
|
| def main(): |
| """主函数""" |
| if len(sys.argv) != 2: |
| print("用法: python api.py <json_file_path>") |
| print("示例: python api.py /path/to/conversations.json") |
| sys.exit(1) |
| |
| json_file_path = sys.argv[1] |
| |
| if not os.path.exists(json_file_path): |
| print(f"错误: 文件不存在 - {json_file_path}") |
| sys.exit(1) |
| |
| |
| ensure_output_directory() |
| |
| |
| process_json_file(json_file_path) |
|
|
| if __name__ == "__main__": |
| main() |